diff --git a/google/cloud/certificate_manager_v1/gapic_metadata.json b/google/cloud/certificate_manager_v1/gapic_metadata.json index b0b60ad..0c07957 100644 --- a/google/cloud/certificate_manager_v1/gapic_metadata.json +++ b/google/cloud/certificate_manager_v1/gapic_metadata.json @@ -256,6 +256,131 @@ ] } } + }, + "rest": { + "libraryClient": "CertificateManagerClient", + "rpcs": { + "CreateCertificate": { + "methods": [ + "create_certificate" + ] + }, + "CreateCertificateIssuanceConfig": { + "methods": [ + "create_certificate_issuance_config" + ] + }, + "CreateCertificateMap": { + "methods": [ + "create_certificate_map" + ] + }, + "CreateCertificateMapEntry": { + "methods": [ + "create_certificate_map_entry" + ] + }, + "CreateDnsAuthorization": { + "methods": [ + "create_dns_authorization" + ] + }, + "DeleteCertificate": { + "methods": [ + "delete_certificate" + ] + }, + "DeleteCertificateIssuanceConfig": { + "methods": [ + "delete_certificate_issuance_config" + ] + }, + "DeleteCertificateMap": { + "methods": [ + "delete_certificate_map" + ] + }, + "DeleteCertificateMapEntry": { + "methods": [ + "delete_certificate_map_entry" + ] + }, + "DeleteDnsAuthorization": { + "methods": [ + "delete_dns_authorization" + ] + }, + "GetCertificate": { + "methods": [ + "get_certificate" + ] + }, + "GetCertificateIssuanceConfig": { + "methods": [ + "get_certificate_issuance_config" + ] + }, + "GetCertificateMap": { + "methods": [ + "get_certificate_map" + ] + }, + "GetCertificateMapEntry": { + "methods": [ + "get_certificate_map_entry" + ] + }, + "GetDnsAuthorization": { + "methods": [ + "get_dns_authorization" + ] + }, + "ListCertificateIssuanceConfigs": { + "methods": [ + "list_certificate_issuance_configs" + ] + }, + "ListCertificateMapEntries": { + "methods": [ + "list_certificate_map_entries" + ] + }, + "ListCertificateMaps": { + "methods": [ + "list_certificate_maps" + ] + }, + "ListCertificates": { + "methods": [ + "list_certificates" + ] + }, + "ListDnsAuthorizations": { + "methods": [ + "list_dns_authorizations" + ] + }, + "UpdateCertificate": { + "methods": [ + "update_certificate" + ] + }, + "UpdateCertificateMap": { + "methods": [ + "update_certificate_map" + ] + }, + "UpdateCertificateMapEntry": { + "methods": [ + "update_certificate_map_entry" + ] + }, + "UpdateDnsAuthorization": { + "methods": [ + "update_dns_authorization" + ] + } + } } } } diff --git a/google/cloud/certificate_manager_v1/services/certificate_manager/client.py b/google/cloud/certificate_manager_v1/services/certificate_manager/client.py index cebac6a..1f905bb 100644 --- a/google/cloud/certificate_manager_v1/services/certificate_manager/client.py +++ b/google/cloud/certificate_manager_v1/services/certificate_manager/client.py @@ -65,6 +65,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, CertificateManagerTransport from .transports.grpc import CertificateManagerGrpcTransport from .transports.grpc_asyncio import CertificateManagerGrpcAsyncIOTransport +from .transports.rest import CertificateManagerRestTransport class CertificateManagerClientMeta(type): @@ -80,6 +81,7 @@ class CertificateManagerClientMeta(type): ) # type: Dict[str, Type[CertificateManagerTransport]] _transport_registry["grpc"] = CertificateManagerGrpcTransport _transport_registry["grpc_asyncio"] = CertificateManagerGrpcAsyncIOTransport + _transport_registry["rest"] = CertificateManagerRestTransport def get_transport_class( cls, diff --git a/google/cloud/certificate_manager_v1/services/certificate_manager/transports/__init__.py b/google/cloud/certificate_manager_v1/services/certificate_manager/transports/__init__.py index 046ef3d..472b196 100644 --- a/google/cloud/certificate_manager_v1/services/certificate_manager/transports/__init__.py +++ b/google/cloud/certificate_manager_v1/services/certificate_manager/transports/__init__.py @@ -19,6 +19,7 @@ from .base import CertificateManagerTransport from .grpc import CertificateManagerGrpcTransport from .grpc_asyncio import CertificateManagerGrpcAsyncIOTransport +from .rest import CertificateManagerRestInterceptor, CertificateManagerRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[CertificateManagerTransport]] _transport_registry["grpc"] = CertificateManagerGrpcTransport _transport_registry["grpc_asyncio"] = CertificateManagerGrpcAsyncIOTransport +_transport_registry["rest"] = CertificateManagerRestTransport __all__ = ( "CertificateManagerTransport", "CertificateManagerGrpcTransport", "CertificateManagerGrpcAsyncIOTransport", + "CertificateManagerRestTransport", + "CertificateManagerRestInterceptor", ) diff --git a/google/cloud/certificate_manager_v1/services/certificate_manager/transports/rest.py b/google/cloud/certificate_manager_v1/services/certificate_manager/transports/rest.py new file mode 100644 index 0000000..ebbe964 --- /dev/null +++ b/google/cloud/certificate_manager_v1/services/certificate_manager/transports/rest.py @@ -0,0 +1,4121 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.certificate_manager_v1.types import certificate_issuance_config +from google.cloud.certificate_manager_v1.types import ( + certificate_issuance_config as gcc_certificate_issuance_config, +) +from google.cloud.certificate_manager_v1.types import certificate_manager + +from .base import CertificateManagerTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CertificateManagerRestInterceptor: + """Interceptor for CertificateManager. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CertificateManagerRestTransport. + + .. code-block:: python + class MyCustomCertificateManagerInterceptor(CertificateManagerRestInterceptor): + def pre_create_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_issuance_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_issuance_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_map_entry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_map_entry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_dns_authorization(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_dns_authorization(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate_issuance_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate_issuance_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate_map_entry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate_map_entry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_dns_authorization(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_dns_authorization(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_issuance_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_issuance_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_map_entry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_map_entry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_dns_authorization(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dns_authorization(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_issuance_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_issuance_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_map_entries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_map_entries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_maps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_maps(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_dns_authorizations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_dns_authorizations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_map_entry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_map_entry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_dns_authorization(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_dns_authorization(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CertificateManagerRestTransport(interceptor=MyCustomCertificateManagerInterceptor()) + client = CertificateManagerClient(transport=transport) + + + """ + + def pre_create_certificate( + self, + request: certificate_manager.CreateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.CreateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_create_certificate( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_issuance_config( + self, + request: gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for create_certificate_issuance_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_create_certificate_issuance_config( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_issuance_config + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_map( + self, + request: certificate_manager.CreateCertificateMapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.CreateCertificateMapRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_certificate_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_create_certificate_map( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_map + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_map_entry( + self, + request: certificate_manager.CreateCertificateMapEntryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.CreateCertificateMapEntryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_certificate_map_entry + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_create_certificate_map_entry( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_map_entry + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_create_dns_authorization( + self, + request: certificate_manager.CreateDnsAuthorizationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.CreateDnsAuthorizationRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_dns_authorization + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_create_dns_authorization( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_dns_authorization + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate( + self, + request: certificate_manager.DeleteCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.DeleteCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_certificate( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate_issuance_config( + self, + request: certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for delete_certificate_issuance_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_certificate_issuance_config( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate_issuance_config + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate_map( + self, + request: certificate_manager.DeleteCertificateMapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.DeleteCertificateMapRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_certificate_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_certificate_map( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate_map + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate_map_entry( + self, + request: certificate_manager.DeleteCertificateMapEntryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.DeleteCertificateMapEntryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_certificate_map_entry + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_certificate_map_entry( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate_map_entry + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_dns_authorization( + self, + request: certificate_manager.DeleteDnsAuthorizationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.DeleteDnsAuthorizationRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_dns_authorization + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_dns_authorization( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_dns_authorization + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_certificate( + self, + request: certificate_manager.GetCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.GetCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_certificate( + self, response: certificate_manager.Certificate + ) -> certificate_manager.Certificate: + """Post-rpc interceptor for get_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_issuance_config( + self, + request: certificate_issuance_config.GetCertificateIssuanceConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_issuance_config.GetCertificateIssuanceConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for get_certificate_issuance_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_certificate_issuance_config( + self, response: certificate_issuance_config.CertificateIssuanceConfig + ) -> certificate_issuance_config.CertificateIssuanceConfig: + """Post-rpc interceptor for get_certificate_issuance_config + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_map( + self, + request: certificate_manager.GetCertificateMapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.GetCertificateMapRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_certificate_map( + self, response: certificate_manager.CertificateMap + ) -> certificate_manager.CertificateMap: + """Post-rpc interceptor for get_certificate_map + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_map_entry( + self, + request: certificate_manager.GetCertificateMapEntryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.GetCertificateMapEntryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_certificate_map_entry + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_certificate_map_entry( + self, response: certificate_manager.CertificateMapEntry + ) -> certificate_manager.CertificateMapEntry: + """Post-rpc interceptor for get_certificate_map_entry + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_dns_authorization( + self, + request: certificate_manager.GetDnsAuthorizationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.GetDnsAuthorizationRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_dns_authorization + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_dns_authorization( + self, response: certificate_manager.DnsAuthorization + ) -> certificate_manager.DnsAuthorization: + """Post-rpc interceptor for get_dns_authorization + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_issuance_configs( + self, + request: certificate_issuance_config.ListCertificateIssuanceConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_issuance_config.ListCertificateIssuanceConfigsRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for list_certificate_issuance_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_certificate_issuance_configs( + self, + response: certificate_issuance_config.ListCertificateIssuanceConfigsResponse, + ) -> certificate_issuance_config.ListCertificateIssuanceConfigsResponse: + """Post-rpc interceptor for list_certificate_issuance_configs + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_map_entries( + self, + request: certificate_manager.ListCertificateMapEntriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.ListCertificateMapEntriesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_certificate_map_entries + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_certificate_map_entries( + self, response: certificate_manager.ListCertificateMapEntriesResponse + ) -> certificate_manager.ListCertificateMapEntriesResponse: + """Post-rpc interceptor for list_certificate_map_entries + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_maps( + self, + request: certificate_manager.ListCertificateMapsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.ListCertificateMapsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_certificate_maps + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_certificate_maps( + self, response: certificate_manager.ListCertificateMapsResponse + ) -> certificate_manager.ListCertificateMapsResponse: + """Post-rpc interceptor for list_certificate_maps + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_certificates( + self, + request: certificate_manager.ListCertificatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.ListCertificatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificates + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_certificates( + self, response: certificate_manager.ListCertificatesResponse + ) -> certificate_manager.ListCertificatesResponse: + """Post-rpc interceptor for list_certificates + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_dns_authorizations( + self, + request: certificate_manager.ListDnsAuthorizationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.ListDnsAuthorizationsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_dns_authorizations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_dns_authorizations( + self, response: certificate_manager.ListDnsAuthorizationsResponse + ) -> certificate_manager.ListDnsAuthorizationsResponse: + """Post-rpc interceptor for list_dns_authorizations + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_update_certificate( + self, + request: certificate_manager.UpdateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[certificate_manager.UpdateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_update_certificate( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_map( + self, + request: certificate_manager.UpdateCertificateMapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.UpdateCertificateMapRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_certificate_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_update_certificate_map( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_map + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_map_entry( + self, + request: certificate_manager.UpdateCertificateMapEntryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.UpdateCertificateMapEntryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_certificate_map_entry + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_update_certificate_map_entry( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_map_entry + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_update_dns_authorization( + self, + request: certificate_manager.UpdateDnsAuthorizationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + certificate_manager.UpdateDnsAuthorizationRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_dns_authorization + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_update_dns_authorization( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_dns_authorization + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.Location: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.GetLocationRequest + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> locations_pb2.ListLocationsResponse: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsRequest + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_cancel_operation( + self, response: operations_pb2.CancelOperationRequest + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_delete_operation( + self, response: operations_pb2.DeleteOperationRequest + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateManager server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsRequest + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the CertificateManager server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CertificateManagerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CertificateManagerRestInterceptor + + +class CertificateManagerRestTransport(CertificateManagerTransport): + """REST backend transport for CertificateManager. + + API Overview + + Certificates Manager API allows customers to see and manage all + their TLS certificates. + + Certificates Manager API service provides methods to manage + certificates, group them into collections, and create serving + configuration that can be easily applied to other Cloud resources + e.g. Target Proxies. + + Data Model + + The Certificates Manager service exposes the following resources: + + - ``Certificate`` that describes a single TLS certificate. + - ``CertificateMap`` that describes a collection of certificates + that can be attached to a target resource. + - ``CertificateMapEntry`` that describes a single configuration + entry that consists of a SNI and a group of certificates. It's a + subresource of CertificateMap. + + Certificate, CertificateMap and CertificateMapEntry IDs have to + fully match the regexp ``[a-z0-9-]{1,63}``. In other words, + + - only lower case letters, digits, and hyphen are allowed + - length of the resource ID has to be in [1,63] range. + + Provides methods to manage Cloud Certificate Manager entities. + + 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 = "certificatemanager.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CertificateManagerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CertificateManagerRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateCertificate(CertificateManagerRestStub): + def __hash__(self): + return hash("CreateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "certificateId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.CreateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate method over HTTP. + + Args: + request (~.certificate_manager.CreateCertificateRequest): + The request object. Request for the ``CreateCertificate`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/certificates", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_create_certificate( + request, metadata + ) + pb_request = certificate_manager.CreateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate(resp) + return resp + + class _CreateCertificateIssuanceConfig(CertificateManagerRestStub): + def __hash__(self): + return hash("CreateCertificateIssuanceConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "certificateIssuanceConfigId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate + issuance config method over HTTP. + + Args: + request (~.gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest): + The request object. Request for the ``CreateCertificateIssuanceConfig`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/certificateIssuanceConfigs", + "body": "certificate_issuance_config", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_create_certificate_issuance_config( + request, metadata + ) + pb_request = gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_issuance_config(resp) + return resp + + class _CreateCertificateMap(CertificateManagerRestStub): + def __hash__(self): + return hash("CreateCertificateMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "certificateMapId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.CreateCertificateMapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate map method over HTTP. + + Args: + request (~.certificate_manager.CreateCertificateMapRequest): + The request object. Request for the ``CreateCertificateMap`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/certificateMaps", + "body": "certificate_map", + }, + ] + request, metadata = self._interceptor.pre_create_certificate_map( + request, metadata + ) + pb_request = certificate_manager.CreateCertificateMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_map(resp) + return resp + + class _CreateCertificateMapEntry(CertificateManagerRestStub): + def __hash__(self): + return hash("CreateCertificateMapEntry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "certificateMapEntryId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.CreateCertificateMapEntryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate map + entry method over HTTP. + + Args: + request (~.certificate_manager.CreateCertificateMapEntryRequest): + The request object. Request for the ``CreateCertificateMapEntry`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/certificateMaps/*}/certificateMapEntries", + "body": "certificate_map_entry", + }, + ] + request, metadata = self._interceptor.pre_create_certificate_map_entry( + request, metadata + ) + pb_request = certificate_manager.CreateCertificateMapEntryRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_map_entry(resp) + return resp + + class _CreateDnsAuthorization(CertificateManagerRestStub): + def __hash__(self): + return hash("CreateDnsAuthorization") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "dnsAuthorizationId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.CreateDnsAuthorizationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create dns authorization method over HTTP. + + Args: + request (~.certificate_manager.CreateDnsAuthorizationRequest): + The request object. Request for the ``CreateDnsAuthorization`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/dnsAuthorizations", + "body": "dns_authorization", + }, + ] + request, metadata = self._interceptor.pre_create_dns_authorization( + request, metadata + ) + pb_request = certificate_manager.CreateDnsAuthorizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_dns_authorization(resp) + return resp + + class _DeleteCertificate(CertificateManagerRestStub): + def __hash__(self): + return hash("DeleteCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.DeleteCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate method over HTTP. + + Args: + request (~.certificate_manager.DeleteCertificateRequest): + The request object. Request for the ``DeleteCertificate`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificates/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_certificate( + request, metadata + ) + pb_request = certificate_manager.DeleteCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate(resp) + return resp + + class _DeleteCertificateIssuanceConfig(CertificateManagerRestStub): + def __hash__(self): + return hash("DeleteCertificateIssuanceConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate + issuance config method over HTTP. + + Args: + request (~.certificate_issuance_config.DeleteCertificateIssuanceConfigRequest): + The request object. Request for the ``DeleteCertificateIssuanceConfig`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificateIssuanceConfigs/*}", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_delete_certificate_issuance_config( + request, metadata + ) + pb_request = ( + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate_issuance_config(resp) + return resp + + class _DeleteCertificateMap(CertificateManagerRestStub): + def __hash__(self): + return hash("DeleteCertificateMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.DeleteCertificateMapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate map method over HTTP. + + Args: + request (~.certificate_manager.DeleteCertificateMapRequest): + The request object. Request for the ``DeleteCertificateMap`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificateMaps/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_certificate_map( + request, metadata + ) + pb_request = certificate_manager.DeleteCertificateMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate_map(resp) + return resp + + class _DeleteCertificateMapEntry(CertificateManagerRestStub): + def __hash__(self): + return hash("DeleteCertificateMapEntry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.DeleteCertificateMapEntryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate map + entry method over HTTP. + + Args: + request (~.certificate_manager.DeleteCertificateMapEntryRequest): + The request object. Request for the ``DeleteCertificateMapEntry`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_certificate_map_entry( + request, metadata + ) + pb_request = certificate_manager.DeleteCertificateMapEntryRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate_map_entry(resp) + return resp + + class _DeleteDnsAuthorization(CertificateManagerRestStub): + def __hash__(self): + return hash("DeleteDnsAuthorization") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.DeleteDnsAuthorizationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete dns authorization method over HTTP. + + Args: + request (~.certificate_manager.DeleteDnsAuthorizationRequest): + The request object. Request for the ``DeleteDnsAuthorization`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/dnsAuthorizations/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_dns_authorization( + request, metadata + ) + pb_request = certificate_manager.DeleteDnsAuthorizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_dns_authorization(resp) + return resp + + class _GetCertificate(CertificateManagerRestStub): + def __hash__(self): + return hash("GetCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.GetCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.Certificate: + r"""Call the get certificate method over HTTP. + + Args: + request (~.certificate_manager.GetCertificateRequest): + The request object. Request for the ``GetCertificate`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.Certificate: + Defines TLS certificate. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate(request, metadata) + pb_request = certificate_manager.GetCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.Certificate() + pb_resp = certificate_manager.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate(resp) + return resp + + class _GetCertificateIssuanceConfig(CertificateManagerRestStub): + def __hash__(self): + return hash("GetCertificateIssuanceConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_issuance_config.GetCertificateIssuanceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_issuance_config.CertificateIssuanceConfig: + r"""Call the get certificate issuance + config method over HTTP. + + Args: + request (~.certificate_issuance_config.GetCertificateIssuanceConfigRequest): + The request object. Request for the ``GetCertificateIssuanceConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_issuance_config.CertificateIssuanceConfig: + CertificateIssuanceConfig specifies + how to issue and manage a certificate. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificateIssuanceConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_issuance_config( + request, metadata + ) + pb_request = ( + certificate_issuance_config.GetCertificateIssuanceConfigRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_issuance_config.CertificateIssuanceConfig() + pb_resp = certificate_issuance_config.CertificateIssuanceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_issuance_config(resp) + return resp + + class _GetCertificateMap(CertificateManagerRestStub): + def __hash__(self): + return hash("GetCertificateMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.GetCertificateMapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.CertificateMap: + r"""Call the get certificate map method over HTTP. + + Args: + request (~.certificate_manager.GetCertificateMapRequest): + The request object. Request for the ``GetCertificateMap`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.CertificateMap: + Defines a collection of certificate + configurations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificateMaps/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_map( + request, metadata + ) + pb_request = certificate_manager.GetCertificateMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.CertificateMap() + pb_resp = certificate_manager.CertificateMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_map(resp) + return resp + + class _GetCertificateMapEntry(CertificateManagerRestStub): + def __hash__(self): + return hash("GetCertificateMapEntry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.GetCertificateMapEntryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.CertificateMapEntry: + r"""Call the get certificate map entry method over HTTP. + + Args: + request (~.certificate_manager.GetCertificateMapEntryRequest): + The request object. Request for the ``GetCertificateMapEntry`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.CertificateMapEntry: + Defines a certificate map entry. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_map_entry( + request, metadata + ) + pb_request = certificate_manager.GetCertificateMapEntryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.CertificateMapEntry() + pb_resp = certificate_manager.CertificateMapEntry.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_map_entry(resp) + return resp + + class _GetDnsAuthorization(CertificateManagerRestStub): + def __hash__(self): + return hash("GetDnsAuthorization") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.GetDnsAuthorizationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.DnsAuthorization: + r"""Call the get dns authorization method over HTTP. + + Args: + request (~.certificate_manager.GetDnsAuthorizationRequest): + The request object. Request for the ``GetDnsAuthorization`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.DnsAuthorization: + A DnsAuthorization resource describes + a way to perform domain authorization + for certificate issuance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dnsAuthorizations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_dns_authorization( + request, metadata + ) + pb_request = certificate_manager.GetDnsAuthorizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.DnsAuthorization() + pb_resp = certificate_manager.DnsAuthorization.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_dns_authorization(resp) + return resp + + class _ListCertificateIssuanceConfigs(CertificateManagerRestStub): + def __hash__(self): + return hash("ListCertificateIssuanceConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_issuance_config.ListCertificateIssuanceConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_issuance_config.ListCertificateIssuanceConfigsResponse: + r"""Call the list certificate issuance + configs method over HTTP. + + Args: + request (~.certificate_issuance_config.ListCertificateIssuanceConfigsRequest): + The request object. Request for the ``ListCertificateIssuanceConfigs`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_issuance_config.ListCertificateIssuanceConfigsResponse: + Response for the ``ListCertificateIssuanceConfigs`` + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/certificateIssuanceConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_issuance_configs( + request, metadata + ) + pb_request = ( + certificate_issuance_config.ListCertificateIssuanceConfigsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_issuance_config.ListCertificateIssuanceConfigsResponse() + pb_resp = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_issuance_configs(resp) + return resp + + class _ListCertificateMapEntries(CertificateManagerRestStub): + def __hash__(self): + return hash("ListCertificateMapEntries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.ListCertificateMapEntriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.ListCertificateMapEntriesResponse: + r"""Call the list certificate map + entries method over HTTP. + + Args: + request (~.certificate_manager.ListCertificateMapEntriesRequest): + The request object. Request for the ``ListCertificateMapEntries`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.ListCertificateMapEntriesResponse: + Response for the ``ListCertificateMapEntries`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/certificateMaps/*}/certificateMapEntries", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_map_entries( + request, metadata + ) + pb_request = certificate_manager.ListCertificateMapEntriesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.ListCertificateMapEntriesResponse() + pb_resp = certificate_manager.ListCertificateMapEntriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_map_entries(resp) + return resp + + class _ListCertificateMaps(CertificateManagerRestStub): + def __hash__(self): + return hash("ListCertificateMaps") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.ListCertificateMapsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.ListCertificateMapsResponse: + r"""Call the list certificate maps method over HTTP. + + Args: + request (~.certificate_manager.ListCertificateMapsRequest): + The request object. Request for the ``ListCertificateMaps`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.ListCertificateMapsResponse: + Response for the ``ListCertificateMaps`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/certificateMaps", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_maps( + request, metadata + ) + pb_request = certificate_manager.ListCertificateMapsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.ListCertificateMapsResponse() + pb_resp = certificate_manager.ListCertificateMapsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_maps(resp) + return resp + + class _ListCertificates(CertificateManagerRestStub): + def __hash__(self): + return hash("ListCertificates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.ListCertificatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.ListCertificatesResponse: + r"""Call the list certificates method over HTTP. + + Args: + request (~.certificate_manager.ListCertificatesRequest): + The request object. Request for the ``ListCertificates`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.ListCertificatesResponse: + Response for the ``ListCertificates`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/certificates", + }, + ] + request, metadata = self._interceptor.pre_list_certificates( + request, metadata + ) + pb_request = certificate_manager.ListCertificatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.ListCertificatesResponse() + pb_resp = certificate_manager.ListCertificatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificates(resp) + return resp + + class _ListDnsAuthorizations(CertificateManagerRestStub): + def __hash__(self): + return hash("ListDnsAuthorizations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.ListDnsAuthorizationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate_manager.ListDnsAuthorizationsResponse: + r"""Call the list dns authorizations method over HTTP. + + Args: + request (~.certificate_manager.ListDnsAuthorizationsRequest): + The request object. Request for the ``ListDnsAuthorizations`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.certificate_manager.ListDnsAuthorizationsResponse: + Response for the ``ListDnsAuthorizations`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/dnsAuthorizations", + }, + ] + request, metadata = self._interceptor.pre_list_dns_authorizations( + request, metadata + ) + pb_request = certificate_manager.ListDnsAuthorizationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = certificate_manager.ListDnsAuthorizationsResponse() + pb_resp = certificate_manager.ListDnsAuthorizationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_dns_authorizations(resp) + return resp + + class _UpdateCertificate(CertificateManagerRestStub): + def __hash__(self): + return hash("UpdateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.UpdateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate method over HTTP. + + Args: + request (~.certificate_manager.UpdateCertificateRequest): + The request object. Request for the ``UpdateCertificate`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate.name=projects/*/locations/*/certificates/*}", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_update_certificate( + request, metadata + ) + pb_request = certificate_manager.UpdateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate(resp) + return resp + + class _UpdateCertificateMap(CertificateManagerRestStub): + def __hash__(self): + return hash("UpdateCertificateMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.UpdateCertificateMapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate map method over HTTP. + + Args: + request (~.certificate_manager.UpdateCertificateMapRequest): + The request object. Request for the ``UpdateCertificateMap`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_map.name=projects/*/locations/*/certificateMaps/*}", + "body": "certificate_map", + }, + ] + request, metadata = self._interceptor.pre_update_certificate_map( + request, metadata + ) + pb_request = certificate_manager.UpdateCertificateMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_map(resp) + return resp + + class _UpdateCertificateMapEntry(CertificateManagerRestStub): + def __hash__(self): + return hash("UpdateCertificateMapEntry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.UpdateCertificateMapEntryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate map + entry method over HTTP. + + Args: + request (~.certificate_manager.UpdateCertificateMapEntryRequest): + The request object. Request for the ``UpdateCertificateMapEntry`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_map_entry.name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}", + "body": "certificate_map_entry", + }, + ] + request, metadata = self._interceptor.pre_update_certificate_map_entry( + request, metadata + ) + pb_request = certificate_manager.UpdateCertificateMapEntryRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_map_entry(resp) + return resp + + class _UpdateDnsAuthorization(CertificateManagerRestStub): + def __hash__(self): + return hash("UpdateDnsAuthorization") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: certificate_manager.UpdateDnsAuthorizationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update dns authorization method over HTTP. + + Args: + request (~.certificate_manager.UpdateDnsAuthorizationRequest): + The request object. Request for the ``UpdateDnsAuthorization`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{dns_authorization.name=projects/*/locations/*/dnsAuthorizations/*}", + "body": "dns_authorization", + }, + ] + request, metadata = self._interceptor.pre_update_dns_authorization( + request, metadata + ) + pb_request = certificate_manager.UpdateDnsAuthorizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_dns_authorization(resp) + return resp + + @property + def create_certificate( + self, + ) -> Callable[ + [certificate_manager.CreateCertificateRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_issuance_config( + self, + ) -> Callable[ + [gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateIssuanceConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_map( + self, + ) -> Callable[ + [certificate_manager.CreateCertificateMapRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_map_entry( + self, + ) -> Callable[ + [certificate_manager.CreateCertificateMapEntryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateMapEntry(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_dns_authorization( + self, + ) -> Callable[ + [certificate_manager.CreateDnsAuthorizationRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDnsAuthorization(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate( + self, + ) -> Callable[ + [certificate_manager.DeleteCertificateRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate_issuance_config( + self, + ) -> Callable[ + [certificate_issuance_config.DeleteCertificateIssuanceConfigRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificateIssuanceConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate_map( + self, + ) -> Callable[ + [certificate_manager.DeleteCertificateMapRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificateMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate_map_entry( + self, + ) -> Callable[ + [certificate_manager.DeleteCertificateMapEntryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificateMapEntry(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_dns_authorization( + self, + ) -> Callable[ + [certificate_manager.DeleteDnsAuthorizationRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDnsAuthorization(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate( + self, + ) -> Callable[ + [certificate_manager.GetCertificateRequest], certificate_manager.Certificate + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_issuance_config( + self, + ) -> Callable[ + [certificate_issuance_config.GetCertificateIssuanceConfigRequest], + certificate_issuance_config.CertificateIssuanceConfig, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateIssuanceConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_map( + self, + ) -> Callable[ + [certificate_manager.GetCertificateMapRequest], + certificate_manager.CertificateMap, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_map_entry( + self, + ) -> Callable[ + [certificate_manager.GetCertificateMapEntryRequest], + certificate_manager.CertificateMapEntry, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateMapEntry(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_dns_authorization( + self, + ) -> Callable[ + [certificate_manager.GetDnsAuthorizationRequest], + certificate_manager.DnsAuthorization, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDnsAuthorization(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_issuance_configs( + self, + ) -> Callable[ + [certificate_issuance_config.ListCertificateIssuanceConfigsRequest], + certificate_issuance_config.ListCertificateIssuanceConfigsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateIssuanceConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_map_entries( + self, + ) -> Callable[ + [certificate_manager.ListCertificateMapEntriesRequest], + certificate_manager.ListCertificateMapEntriesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateMapEntries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_maps( + self, + ) -> Callable[ + [certificate_manager.ListCertificateMapsRequest], + certificate_manager.ListCertificateMapsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateMaps(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificates( + self, + ) -> Callable[ + [certificate_manager.ListCertificatesRequest], + certificate_manager.ListCertificatesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_dns_authorizations( + self, + ) -> Callable[ + [certificate_manager.ListDnsAuthorizationsRequest], + certificate_manager.ListDnsAuthorizationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDnsAuthorizations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate( + self, + ) -> Callable[ + [certificate_manager.UpdateCertificateRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_map( + self, + ) -> Callable[ + [certificate_manager.UpdateCertificateMapRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_map_entry( + self, + ) -> Callable[ + [certificate_manager.UpdateCertificateMapEntryRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateMapEntry(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_dns_authorization( + self, + ) -> Callable[ + [certificate_manager.UpdateDnsAuthorizationRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDnsAuthorization(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(CertificateManagerRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(CertificateManagerRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(CertificateManagerRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(CertificateManagerRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(CertificateManagerRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(CertificateManagerRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CertificateManagerRestTransport",) diff --git a/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py b/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py index fe2270b..c0f1ad0 100644 --- a/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py +++ b/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -45,12 +47,15 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.certificate_manager_v1.services.certificate_manager import ( CertificateManagerAsyncClient, @@ -115,6 +120,7 @@ def test__get_default_mtls_endpoint(): [ (CertificateManagerClient, "grpc"), (CertificateManagerAsyncClient, "grpc_asyncio"), + (CertificateManagerClient, "rest"), ], ) def test_certificate_manager_client_from_service_account_info( @@ -130,7 +136,11 @@ def test_certificate_manager_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("certificatemanager.googleapis.com:443") + assert client.transport._host == ( + "certificatemanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://certificatemanager.googleapis.com" + ) @pytest.mark.parametrize( @@ -138,6 +148,7 @@ def test_certificate_manager_client_from_service_account_info( [ (transports.CertificateManagerGrpcTransport, "grpc"), (transports.CertificateManagerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CertificateManagerRestTransport, "rest"), ], ) def test_certificate_manager_client_service_account_always_use_jwt( @@ -163,6 +174,7 @@ def test_certificate_manager_client_service_account_always_use_jwt( [ (CertificateManagerClient, "grpc"), (CertificateManagerAsyncClient, "grpc_asyncio"), + (CertificateManagerClient, "rest"), ], ) def test_certificate_manager_client_from_service_account_file( @@ -185,13 +197,18 @@ def test_certificate_manager_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("certificatemanager.googleapis.com:443") + assert client.transport._host == ( + "certificatemanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://certificatemanager.googleapis.com" + ) def test_certificate_manager_client_get_transport_class(): transport = CertificateManagerClient.get_transport_class() available_transports = [ transports.CertificateManagerGrpcTransport, + transports.CertificateManagerRestTransport, ] assert transport in available_transports @@ -208,6 +225,7 @@ def test_certificate_manager_client_get_transport_class(): transports.CertificateManagerGrpcAsyncIOTransport, "grpc_asyncio", ), + (CertificateManagerClient, transports.CertificateManagerRestTransport, "rest"), ], ) @mock.patch.object( @@ -363,6 +381,18 @@ def test_certificate_manager_client_client_options( "grpc_asyncio", "false", ), + ( + CertificateManagerClient, + transports.CertificateManagerRestTransport, + "rest", + "true", + ), + ( + CertificateManagerClient, + transports.CertificateManagerRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -562,6 +592,7 @@ def test_certificate_manager_client_get_mtls_endpoint_and_cert_source(client_cla transports.CertificateManagerGrpcAsyncIOTransport, "grpc_asyncio", ), + (CertificateManagerClient, transports.CertificateManagerRestTransport, "rest"), ], ) def test_certificate_manager_client_client_options_scopes( @@ -602,6 +633,12 @@ def test_certificate_manager_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + CertificateManagerClient, + transports.CertificateManagerRestTransport, + "rest", + None, + ), ], ) def test_certificate_manager_client_client_options_credentials_file( @@ -7827,141 +7864,7674 @@ async def test_delete_certificate_issuance_config_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CertificateManagerGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.ListCertificatesRequest, + dict, + ], +) +def test_list_certificates_rest(request_type): + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CertificateManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CertificateManagerGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificates_rest_required_fields( + request_type=certificate_manager.ListCertificatesRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificates._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_certificates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListCertificatesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.ListCertificatesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificates_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = CertificateManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + unset_fields = transport.list_certificates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CertificateManagerGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificates_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateManagerClient( - client_options=options, - transport=transport, + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_list_certificates" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_list_certificates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.ListCertificatesRequest.pb( + certificate_manager.ListCertificatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_manager.ListCertificatesResponse.to_json( + certificate_manager.ListCertificatesResponse() + ) ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateManagerClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = certificate_manager.ListCertificatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.ListCertificatesResponse() + + client.list_certificates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.CertificateManagerGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificates_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.ListCertificatesRequest +): + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = CertificateManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateManagerGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificates(request) + + +def test_list_certificates_rest_flattened(): + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CertificateManagerClient(transport=transport) - assert client.transport is transport + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListCertificatesResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateManagerGrpcTransport( + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificates(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_list_certificates_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.CertificateManagerGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificates( + certificate_manager.ListCertificatesRequest(), + parent="parent_value", + ) + + +def test_list_certificates_rest_pager(transport: str = "rest"): + client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + certificate_manager.ListCertificatesResponse( + certificates=[ + certificate_manager.Certificate(), + certificate_manager.Certificate(), + certificate_manager.Certificate(), + ], + next_page_token="abc", + ), + certificate_manager.ListCertificatesResponse( + certificates=[], + next_page_token="def", + ), + certificate_manager.ListCertificatesResponse( + certificates=[ + certificate_manager.Certificate(), + ], + next_page_token="ghi", + ), + certificate_manager.ListCertificatesResponse( + certificates=[ + certificate_manager.Certificate(), + certificate_manager.Certificate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + certificate_manager.ListCertificatesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateManagerGrpcTransport, - transports.CertificateManagerGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_certificates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, certificate_manager.Certificate) for i in results) + + pages = list(client.list_certificates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + certificate_manager.GetCertificateRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = CertificateManagerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_get_certificate_rest(request_type): client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CertificateManagerGrpcTransport, + transport="rest", ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/certificates/sample3"} + request = request_type(**request_init) -def test_certificate_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CertificateManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # 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 = certificate_manager.Certificate( + name="name_value", + description="description_value", + san_dnsnames=["san_dnsnames_value"], + pem_certificate="pem_certificate_value", + scope=certificate_manager.Certificate.Scope.EDGE_CACHE, + self_managed=certificate_manager.Certificate.SelfManagedCertificate( + pem_certificate="pem_certificate_value" + ), ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_certificate_manager_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.certificate_manager_v1.services.certificate_manager.transports.CertificateManagerTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CertificateManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate_manager.Certificate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.san_dnsnames == ["san_dnsnames_value"] + assert response.pem_certificate == "pem_certificate_value" + assert response.scope == certificate_manager.Certificate.Scope.EDGE_CACHE + + +def test_get_certificate_rest_required_fields( + request_type=certificate_manager.GetCertificateRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # Every method on the transport should just blindly + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate._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_certificate._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_get_certificate" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_get_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.GetCertificateRequest.pb( + certificate_manager.GetCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = certificate_manager.Certificate.to_json( + certificate_manager.Certificate() + ) + + request = certificate_manager.GetCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.Certificate() + + client.get_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.GetCertificateRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/certificates/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate(request) + + +def test_get_certificate_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificates/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate( + certificate_manager.GetCertificateRequest(), + name="name_value", + ) + + +def test_get_certificate_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.CreateCertificateRequest, + dict, + ], +) +def test_create_certificate_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "self_managed": { + "pem_certificate": "pem_certificate_value", + "pem_private_key": "pem_private_key_value", + }, + "managed": { + "domains": ["domains_value1", "domains_value2"], + "dns_authorizations": [ + "dns_authorizations_value1", + "dns_authorizations_value2", + ], + "issuance_config": "issuance_config_value", + "state": 1, + "provisioning_issue": {"reason": 1, "details": "details_value"}, + "authorization_attempt_info": [ + { + "domain": "domain_value", + "state": 1, + "failure_reason": 1, + "details": "details_value", + } + ], + }, + "san_dnsnames": ["san_dnsnames_value1", "san_dnsnames_value2"], + "pem_certificate": "pem_certificate_value", + "expire_time": {}, + "scope": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_rest_required_fields( + request_type=certificate_manager.CreateCertificateRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateId" in jsonified_request + assert jsonified_request["certificateId"] == request_init["certificate_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateId"] = "certificate_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("certificate_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 "certificateId" in jsonified_request + assert jsonified_request["certificateId"] == "certificate_id_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate(request) + + expected_params = [ + ( + "certificateId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("certificateId",)) + & set( + ( + "parent", + "certificateId", + "certificate", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_create_certificate" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_create_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.CreateCertificateRequest.pb( + certificate_manager.CreateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.CreateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.CreateCertificateRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "self_managed": { + "pem_certificate": "pem_certificate_value", + "pem_private_key": "pem_private_key_value", + }, + "managed": { + "domains": ["domains_value1", "domains_value2"], + "dns_authorizations": [ + "dns_authorizations_value1", + "dns_authorizations_value2", + ], + "issuance_config": "issuance_config_value", + "state": 1, + "provisioning_issue": {"reason": 1, "details": "details_value"}, + "authorization_attempt_info": [ + { + "domain": "domain_value", + "state": 1, + "failure_reason": 1, + "details": "details_value", + } + ], + }, + "san_dnsnames": ["san_dnsnames_value1", "san_dnsnames_value2"], + "pem_certificate": "pem_certificate_value", + "expire_time": {}, + "scope": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate(request) + + +def test_create_certificate_rest_flattened(): + client = CertificateManagerClient( + 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", + certificate=certificate_manager.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate( + certificate_manager.CreateCertificateRequest(), + parent="parent_value", + certificate=certificate_manager.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) + + +def test_create_certificate_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.UpdateCertificateRequest, + dict, + ], +) +def test_update_certificate_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificates/sample3" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/certificates/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "self_managed": { + "pem_certificate": "pem_certificate_value", + "pem_private_key": "pem_private_key_value", + }, + "managed": { + "domains": ["domains_value1", "domains_value2"], + "dns_authorizations": [ + "dns_authorizations_value1", + "dns_authorizations_value2", + ], + "issuance_config": "issuance_config_value", + "state": 1, + "provisioning_issue": {"reason": 1, "details": "details_value"}, + "authorization_attempt_info": [ + { + "domain": "domain_value", + "state": 1, + "failure_reason": 1, + "details": "details_value", + } + ], + }, + "san_dnsnames": ["san_dnsnames_value1", "san_dnsnames_value2"], + "pem_certificate": "pem_certificate_value", + "expire_time": {}, + "scope": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_rest_required_fields( + request_type=certificate_manager.UpdateCertificateRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate._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_certificate._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "certificate", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_update_certificate" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_update_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.UpdateCertificateRequest.pb( + certificate_manager.UpdateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.UpdateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.UpdateCertificateRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificates/sample3" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/certificates/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "self_managed": { + "pem_certificate": "pem_certificate_value", + "pem_private_key": "pem_private_key_value", + }, + "managed": { + "domains": ["domains_value1", "domains_value2"], + "dns_authorizations": [ + "dns_authorizations_value1", + "dns_authorizations_value2", + ], + "issuance_config": "issuance_config_value", + "state": 1, + "provisioning_issue": {"reason": 1, "details": "details_value"}, + "authorization_attempt_info": [ + { + "domain": "domain_value", + "state": 1, + "failure_reason": 1, + "details": "details_value", + } + ], + }, + "san_dnsnames": ["san_dnsnames_value1", "san_dnsnames_value2"], + "pem_certificate": "pem_certificate_value", + "expire_time": {}, + "scope": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate(request) + + +def test_update_certificate_rest_flattened(): + client = CertificateManagerClient( + 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 = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificates/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate=certificate_manager.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate.name=projects/*/locations/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate( + certificate_manager.UpdateCertificateRequest(), + certificate=certificate_manager.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.DeleteCertificateRequest, + dict, + ], +) +def test_delete_certificate_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/certificates/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_rest_required_fields( + request_type=certificate_manager.DeleteCertificateRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate._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_certificate._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_delete_certificate" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_delete_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.DeleteCertificateRequest.pb( + certificate_manager.DeleteCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.DeleteCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.DeleteCertificateRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/certificates/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate(request) + + +def test_delete_certificate_rest_flattened(): + client = CertificateManagerClient( + 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/certificates/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate( + certificate_manager.DeleteCertificateRequest(), + name="name_value", + ) + + +def test_delete_certificate_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.ListCertificateMapsRequest, + dict, + ], +) +def test_list_certificate_maps_rest(request_type): + client = CertificateManagerClient( + 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 = certificate_manager.ListCertificateMapsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificateMapsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_maps(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateMapsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_maps_rest_required_fields( + request_type=certificate_manager.ListCertificateMapsRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_maps._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_certificate_maps._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListCertificateMapsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.ListCertificateMapsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_maps(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_maps_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_maps._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_maps_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_list_certificate_maps" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_list_certificate_maps" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.ListCertificateMapsRequest.pb( + certificate_manager.ListCertificateMapsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_manager.ListCertificateMapsResponse.to_json( + certificate_manager.ListCertificateMapsResponse() + ) + ) + + request = certificate_manager.ListCertificateMapsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.ListCertificateMapsResponse() + + client.list_certificate_maps( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_maps_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.ListCertificateMapsRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_maps(request) + + +def test_list_certificate_maps_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.ListCertificateMapsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificateMapsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_maps(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateMaps" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_maps_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_maps( + certificate_manager.ListCertificateMapsRequest(), + parent="parent_value", + ) + + +def test_list_certificate_maps_rest_pager(transport: str = "rest"): + client = CertificateManagerClient( + 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 = ( + certificate_manager.ListCertificateMapsResponse( + certificate_maps=[ + certificate_manager.CertificateMap(), + certificate_manager.CertificateMap(), + certificate_manager.CertificateMap(), + ], + next_page_token="abc", + ), + certificate_manager.ListCertificateMapsResponse( + certificate_maps=[], + next_page_token="def", + ), + certificate_manager.ListCertificateMapsResponse( + certificate_maps=[ + certificate_manager.CertificateMap(), + ], + next_page_token="ghi", + ), + certificate_manager.ListCertificateMapsResponse( + certificate_maps=[ + certificate_manager.CertificateMap(), + certificate_manager.CertificateMap(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + certificate_manager.ListCertificateMapsResponse.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_certificate_maps(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, certificate_manager.CertificateMap) for i in results) + + pages = list(client.list_certificate_maps(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.GetCertificateMapRequest, + dict, + ], +) +def test_get_certificate_map_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/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 = certificate_manager.CertificateMap( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.CertificateMap.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate_manager.CertificateMap) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_certificate_map_rest_required_fields( + request_type=certificate_manager.GetCertificateMapRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_map._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_certificate_map._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.CertificateMap() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.CertificateMap.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_map(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_map_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_map_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_get_certificate_map" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_get_certificate_map" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.GetCertificateMapRequest.pb( + certificate_manager.GetCertificateMapRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = certificate_manager.CertificateMap.to_json( + certificate_manager.CertificateMap() + ) + + request = certificate_manager.GetCertificateMapRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.CertificateMap() + + client.get_certificate_map( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_map_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.GetCertificateMapRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_map(request) + + +def test_get_certificate_map_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.CertificateMap() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.CertificateMap.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateMaps/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_map_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map( + certificate_manager.GetCertificateMapRequest(), + name="name_value", + ) + + +def test_get_certificate_map_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.CreateCertificateMapRequest, + dict, + ], +) +def test_create_certificate_map_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_map"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "gclb_targets": [ + { + "target_https_proxy": "target_https_proxy_value", + "target_ssl_proxy": "target_ssl_proxy_value", + "ip_configs": [{"ip_address": "ip_address_value", "ports": [569, 570]}], + } + ], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_map(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_map_rest_required_fields( + request_type=certificate_manager.CreateCertificateMapRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_map_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateMapId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_map._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateMapId" in jsonified_request + assert jsonified_request["certificateMapId"] == request_init["certificate_map_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateMapId"] = "certificate_map_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_map._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("certificate_map_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 "certificateMapId" in jsonified_request + assert jsonified_request["certificateMapId"] == "certificate_map_id_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_map(request) + + expected_params = [ + ( + "certificateMapId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_map_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate_map._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("certificateMapId",)) + & set( + ( + "parent", + "certificateMapId", + "certificateMap", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_map_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_create_certificate_map" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_create_certificate_map" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.CreateCertificateMapRequest.pb( + certificate_manager.CreateCertificateMapRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.CreateCertificateMapRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_map( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_map_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.CreateCertificateMapRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_map"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "gclb_targets": [ + { + "target_https_proxy": "target_https_proxy_value", + "target_ssl_proxy": "target_ssl_proxy_value", + "ip_configs": [{"ip_address": "ip_address_value", "ports": [569, 570]}], + } + ], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_map(request) + + +def test_create_certificate_map_rest_flattened(): + client = CertificateManagerClient( + 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", + certificate_map=certificate_manager.CertificateMap(name="name_value"), + certificate_map_id="certificate_map_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateMaps" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_map_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map( + certificate_manager.CreateCertificateMapRequest(), + parent="parent_value", + certificate_map=certificate_manager.CertificateMap(name="name_value"), + certificate_map_id="certificate_map_id_value", + ) + + +def test_create_certificate_map_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.UpdateCertificateMapRequest, + dict, + ], +) +def test_update_certificate_map_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_map": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + } + request_init["certificate_map"] = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "gclb_targets": [ + { + "target_https_proxy": "target_https_proxy_value", + "target_ssl_proxy": "target_ssl_proxy_value", + "ip_configs": [{"ip_address": "ip_address_value", "ports": [569, 570]}], + } + ], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_map(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_map_rest_required_fields( + request_type=certificate_manager.UpdateCertificateMapRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_map._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_certificate_map._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_map(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_map_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_map._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "certificateMap", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_map_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_update_certificate_map" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_update_certificate_map" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.UpdateCertificateMapRequest.pb( + certificate_manager.UpdateCertificateMapRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.UpdateCertificateMapRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_map( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_map_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.UpdateCertificateMapRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_map": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + } + request_init["certificate_map"] = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "gclb_targets": [ + { + "target_https_proxy": "target_https_proxy_value", + "target_ssl_proxy": "target_ssl_proxy_value", + "ip_configs": [{"ip_address": "ip_address_value", "ports": [569, 570]}], + } + ], + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_map(request) + + +def test_update_certificate_map_rest_flattened(): + client = CertificateManagerClient( + 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 = { + "certificate_map": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_map=certificate_manager.CertificateMap(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate_map.name=projects/*/locations/*/certificateMaps/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_map_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map( + certificate_manager.UpdateCertificateMapRequest(), + certificate_map=certificate_manager.CertificateMap(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_map_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.DeleteCertificateMapRequest, + dict, + ], +) +def test_delete_certificate_map_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_map(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_map_rest_required_fields( + request_type=certificate_manager.DeleteCertificateMapRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_map._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_certificate_map._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate_map(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_map_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_certificate_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_map_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_delete_certificate_map" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_delete_certificate_map" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.DeleteCertificateMapRequest.pb( + certificate_manager.DeleteCertificateMapRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.DeleteCertificateMapRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_map( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_map_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.DeleteCertificateMapRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate_map(request) + + +def test_delete_certificate_map_rest_flattened(): + client = CertificateManagerClient( + 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/certificateMaps/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateMaps/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_map_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map( + certificate_manager.DeleteCertificateMapRequest(), + name="name_value", + ) + + +def test_delete_certificate_map_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.ListCertificateMapEntriesRequest, + dict, + ], +) +def test_list_certificate_map_entries_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateMaps/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 = certificate_manager.ListCertificateMapEntriesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificateMapEntriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_map_entries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateMapEntriesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_map_entries_rest_required_fields( + request_type=certificate_manager.ListCertificateMapEntriesRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_map_entries._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_certificate_map_entries._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListCertificateMapEntriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.ListCertificateMapEntriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_map_entries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_map_entries_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_map_entries._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_map_entries_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_list_certificate_map_entries", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_list_certificate_map_entries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.ListCertificateMapEntriesRequest.pb( + certificate_manager.ListCertificateMapEntriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_manager.ListCertificateMapEntriesResponse.to_json( + certificate_manager.ListCertificateMapEntriesResponse() + ) + ) + + request = certificate_manager.ListCertificateMapEntriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.ListCertificateMapEntriesResponse() + + client.list_certificate_map_entries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_map_entries_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.ListCertificateMapEntriesRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_map_entries(request) + + +def test_list_certificate_map_entries_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.ListCertificateMapEntriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListCertificateMapEntriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_map_entries(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/certificateMaps/*}/certificateMapEntries" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_map_entries_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map_entries( + certificate_manager.ListCertificateMapEntriesRequest(), + parent="parent_value", + ) + + +def test_list_certificate_map_entries_rest_pager(transport: str = "rest"): + client = CertificateManagerClient( + 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 = ( + certificate_manager.ListCertificateMapEntriesResponse( + certificate_map_entries=[ + certificate_manager.CertificateMapEntry(), + certificate_manager.CertificateMapEntry(), + certificate_manager.CertificateMapEntry(), + ], + next_page_token="abc", + ), + certificate_manager.ListCertificateMapEntriesResponse( + certificate_map_entries=[], + next_page_token="def", + ), + certificate_manager.ListCertificateMapEntriesResponse( + certificate_map_entries=[ + certificate_manager.CertificateMapEntry(), + ], + next_page_token="ghi", + ), + certificate_manager.ListCertificateMapEntriesResponse( + certificate_map_entries=[ + certificate_manager.CertificateMapEntry(), + certificate_manager.CertificateMapEntry(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + certificate_manager.ListCertificateMapEntriesResponse.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/certificateMaps/sample3" + } + + pager = client.list_certificate_map_entries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, certificate_manager.CertificateMapEntry) for i in results + ) + + pages = list(client.list_certificate_map_entries(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.GetCertificateMapEntryRequest, + dict, + ], +) +def test_get_certificate_map_entry_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = certificate_manager.CertificateMapEntry( + name="name_value", + description="description_value", + certificates=["certificates_value"], + state=certificate_manager.ServingState.ACTIVE, + hostname="hostname_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.CertificateMapEntry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_map_entry(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate_manager.CertificateMapEntry) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.certificates == ["certificates_value"] + assert response.state == certificate_manager.ServingState.ACTIVE + + +def test_get_certificate_map_entry_rest_required_fields( + request_type=certificate_manager.GetCertificateMapEntryRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_map_entry._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_certificate_map_entry._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.CertificateMapEntry() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.CertificateMapEntry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_map_entry(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_map_entry_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_map_entry._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_map_entry_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_get_certificate_map_entry" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_get_certificate_map_entry" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.GetCertificateMapEntryRequest.pb( + certificate_manager.GetCertificateMapEntryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = certificate_manager.CertificateMapEntry.to_json( + certificate_manager.CertificateMapEntry() + ) + + request = certificate_manager.GetCertificateMapEntryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.CertificateMapEntry() + + client.get_certificate_map_entry( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_map_entry_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.GetCertificateMapEntryRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_map_entry(request) + + +def test_get_certificate_map_entry_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.CertificateMapEntry() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.CertificateMapEntry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_map_entry(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_map_entry_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map_entry( + certificate_manager.GetCertificateMapEntryRequest(), + name="name_value", + ) + + +def test_get_certificate_map_entry_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.CreateCertificateMapEntryRequest, + dict, + ], +) +def test_create_certificate_map_entry_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request_init["certificate_map_entry"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "hostname": "hostname_value", + "matcher": 1, + "certificates": ["certificates_value1", "certificates_value2"], + "state": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_map_entry(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_map_entry_rest_required_fields( + request_type=certificate_manager.CreateCertificateMapEntryRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_map_entry_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateMapEntryId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_map_entry._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateMapEntryId" in jsonified_request + assert ( + jsonified_request["certificateMapEntryId"] + == request_init["certificate_map_entry_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateMapEntryId"] = "certificate_map_entry_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_map_entry._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("certificate_map_entry_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 "certificateMapEntryId" in jsonified_request + assert ( + jsonified_request["certificateMapEntryId"] == "certificate_map_entry_id_value" + ) + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_map_entry(request) + + expected_params = [ + ( + "certificateMapEntryId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_map_entry_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate_map_entry._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("certificateMapEntryId",)) + & set( + ( + "parent", + "certificateMapEntryId", + "certificateMapEntry", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_map_entry_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_create_certificate_map_entry", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_create_certificate_map_entry" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.CreateCertificateMapEntryRequest.pb( + certificate_manager.CreateCertificateMapEntryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.CreateCertificateMapEntryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_map_entry( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_map_entry_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.CreateCertificateMapEntryRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateMaps/sample3" + } + request_init["certificate_map_entry"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "hostname": "hostname_value", + "matcher": 1, + "certificates": ["certificates_value1", "certificates_value2"], + "state": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_map_entry(request) + + +def test_create_certificate_map_entry_rest_flattened(): + client = CertificateManagerClient( + 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/certificateMaps/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate_map_entry=certificate_manager.CertificateMapEntry( + name="name_value" + ), + certificate_map_entry_id="certificate_map_entry_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_map_entry(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/certificateMaps/*}/certificateMapEntries" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_map_entry_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map_entry( + certificate_manager.CreateCertificateMapEntryRequest(), + parent="parent_value", + certificate_map_entry=certificate_manager.CertificateMapEntry( + name="name_value" + ), + certificate_map_entry_id="certificate_map_entry_id_value", + ) + + +def test_create_certificate_map_entry_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.UpdateCertificateMapEntryRequest, + dict, + ], +) +def test_update_certificate_map_entry_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_map_entry": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + } + request_init["certificate_map_entry"] = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "hostname": "hostname_value", + "matcher": 1, + "certificates": ["certificates_value1", "certificates_value2"], + "state": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_map_entry(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_map_entry_rest_required_fields( + request_type=certificate_manager.UpdateCertificateMapEntryRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_map_entry._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_certificate_map_entry._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_map_entry(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_map_entry_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_map_entry._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "certificateMapEntry", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_map_entry_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_update_certificate_map_entry", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_update_certificate_map_entry" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.UpdateCertificateMapEntryRequest.pb( + certificate_manager.UpdateCertificateMapEntryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.UpdateCertificateMapEntryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_map_entry( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_map_entry_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.UpdateCertificateMapEntryRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_map_entry": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + } + request_init["certificate_map_entry"] = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "hostname": "hostname_value", + "matcher": 1, + "certificates": ["certificates_value1", "certificates_value2"], + "state": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_map_entry(request) + + +def test_update_certificate_map_entry_rest_flattened(): + client = CertificateManagerClient( + 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 = { + "certificate_map_entry": { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_map_entry=certificate_manager.CertificateMapEntry( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_map_entry(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate_map_entry.name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_map_entry_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map_entry( + certificate_manager.UpdateCertificateMapEntryRequest(), + certificate_map_entry=certificate_manager.CertificateMapEntry( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_map_entry_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.DeleteCertificateMapEntryRequest, + dict, + ], +) +def test_delete_certificate_map_entry_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_map_entry(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_map_entry_rest_required_fields( + request_type=certificate_manager.DeleteCertificateMapEntryRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_map_entry._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_certificate_map_entry._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate_map_entry(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_map_entry_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_certificate_map_entry._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_map_entry_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_delete_certificate_map_entry", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_delete_certificate_map_entry" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.DeleteCertificateMapEntryRequest.pb( + certificate_manager.DeleteCertificateMapEntryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.DeleteCertificateMapEntryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_map_entry( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_map_entry_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.DeleteCertificateMapEntryRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateMaps/sample3/certificateMapEntries/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate_map_entry(request) + + +def test_delete_certificate_map_entry_rest_flattened(): + client = CertificateManagerClient( + 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/certificateMaps/sample3/certificateMapEntries/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate_map_entry(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateMaps/*/certificateMapEntries/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_map_entry_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_map_entry( + certificate_manager.DeleteCertificateMapEntryRequest(), + name="name_value", + ) + + +def test_delete_certificate_map_entry_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.ListDnsAuthorizationsRequest, + dict, + ], +) +def test_list_dns_authorizations_rest(request_type): + client = CertificateManagerClient( + 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 = certificate_manager.ListDnsAuthorizationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListDnsAuthorizationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_dns_authorizations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDnsAuthorizationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_dns_authorizations_rest_required_fields( + request_type=certificate_manager.ListDnsAuthorizationsRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_dns_authorizations._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_dns_authorizations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.ListDnsAuthorizationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.ListDnsAuthorizationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_dns_authorizations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_dns_authorizations_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_dns_authorizations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_dns_authorizations_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_list_dns_authorizations" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_list_dns_authorizations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.ListDnsAuthorizationsRequest.pb( + certificate_manager.ListDnsAuthorizationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_manager.ListDnsAuthorizationsResponse.to_json( + certificate_manager.ListDnsAuthorizationsResponse() + ) + ) + + request = certificate_manager.ListDnsAuthorizationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.ListDnsAuthorizationsResponse() + + client.list_dns_authorizations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_dns_authorizations_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.ListDnsAuthorizationsRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_dns_authorizations(request) + + +def test_list_dns_authorizations_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.ListDnsAuthorizationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.ListDnsAuthorizationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_dns_authorizations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/dnsAuthorizations" + % client.transport._host, + args[1], + ) + + +def test_list_dns_authorizations_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_dns_authorizations( + certificate_manager.ListDnsAuthorizationsRequest(), + parent="parent_value", + ) + + +def test_list_dns_authorizations_rest_pager(transport: str = "rest"): + client = CertificateManagerClient( + 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 = ( + certificate_manager.ListDnsAuthorizationsResponse( + dns_authorizations=[ + certificate_manager.DnsAuthorization(), + certificate_manager.DnsAuthorization(), + certificate_manager.DnsAuthorization(), + ], + next_page_token="abc", + ), + certificate_manager.ListDnsAuthorizationsResponse( + dns_authorizations=[], + next_page_token="def", + ), + certificate_manager.ListDnsAuthorizationsResponse( + dns_authorizations=[ + certificate_manager.DnsAuthorization(), + ], + next_page_token="ghi", + ), + certificate_manager.ListDnsAuthorizationsResponse( + dns_authorizations=[ + certificate_manager.DnsAuthorization(), + certificate_manager.DnsAuthorization(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + certificate_manager.ListDnsAuthorizationsResponse.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_dns_authorizations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, certificate_manager.DnsAuthorization) for i in results) + + pages = list(client.list_dns_authorizations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.GetDnsAuthorizationRequest, + dict, + ], +) +def test_get_dns_authorization_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/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 = certificate_manager.DnsAuthorization( + name="name_value", + description="description_value", + domain="domain_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.DnsAuthorization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_dns_authorization(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate_manager.DnsAuthorization) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.domain == "domain_value" + + +def test_get_dns_authorization_rest_required_fields( + request_type=certificate_manager.GetDnsAuthorizationRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_dns_authorization._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_dns_authorization._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_manager.DnsAuthorization() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_manager.DnsAuthorization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_dns_authorization(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_dns_authorization_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_dns_authorization._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_dns_authorization_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_get_dns_authorization" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_get_dns_authorization" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.GetDnsAuthorizationRequest.pb( + certificate_manager.GetDnsAuthorizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = certificate_manager.DnsAuthorization.to_json( + certificate_manager.DnsAuthorization() + ) + + request = certificate_manager.GetDnsAuthorizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_manager.DnsAuthorization() + + client.get_dns_authorization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_dns_authorization_rest_bad_request( + transport: str = "rest", request_type=certificate_manager.GetDnsAuthorizationRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_dns_authorization(request) + + +def test_get_dns_authorization_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_manager.DnsAuthorization() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_manager.DnsAuthorization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_dns_authorization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/dnsAuthorizations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_dns_authorization_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_dns_authorization( + certificate_manager.GetDnsAuthorizationRequest(), + name="name_value", + ) + + +def test_get_dns_authorization_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.CreateDnsAuthorizationRequest, + dict, + ], +) +def test_create_dns_authorization_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["dns_authorization"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "domain": "domain_value", + "dns_resource_record": { + "name": "name_value", + "type_": "type__value", + "data": "data_value", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_dns_authorization(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_dns_authorization_rest_required_fields( + request_type=certificate_manager.CreateDnsAuthorizationRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["dns_authorization_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "dnsAuthorizationId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dns_authorization._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "dnsAuthorizationId" in jsonified_request + assert ( + jsonified_request["dnsAuthorizationId"] == request_init["dns_authorization_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["dnsAuthorizationId"] = "dns_authorization_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dns_authorization._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("dns_authorization_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 "dnsAuthorizationId" in jsonified_request + assert jsonified_request["dnsAuthorizationId"] == "dns_authorization_id_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_dns_authorization(request) + + expected_params = [ + ( + "dnsAuthorizationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_dns_authorization_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_dns_authorization._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("dnsAuthorizationId",)) + & set( + ( + "parent", + "dnsAuthorizationId", + "dnsAuthorization", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_dns_authorization_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_create_dns_authorization" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_create_dns_authorization" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.CreateDnsAuthorizationRequest.pb( + certificate_manager.CreateDnsAuthorizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.CreateDnsAuthorizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_dns_authorization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_dns_authorization_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.CreateDnsAuthorizationRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["dns_authorization"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "domain": "domain_value", + "dns_resource_record": { + "name": "name_value", + "type_": "type__value", + "data": "data_value", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_dns_authorization(request) + + +def test_create_dns_authorization_rest_flattened(): + client = CertificateManagerClient( + 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", + dns_authorization=certificate_manager.DnsAuthorization(name="name_value"), + dns_authorization_id="dns_authorization_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_dns_authorization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/dnsAuthorizations" + % client.transport._host, + args[1], + ) + + +def test_create_dns_authorization_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_dns_authorization( + certificate_manager.CreateDnsAuthorizationRequest(), + parent="parent_value", + dns_authorization=certificate_manager.DnsAuthorization(name="name_value"), + dns_authorization_id="dns_authorization_id_value", + ) + + +def test_create_dns_authorization_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.UpdateDnsAuthorizationRequest, + dict, + ], +) +def test_update_dns_authorization_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "dns_authorization": { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + } + request_init["dns_authorization"] = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "domain": "domain_value", + "dns_resource_record": { + "name": "name_value", + "type_": "type__value", + "data": "data_value", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_dns_authorization(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_dns_authorization_rest_required_fields( + request_type=certificate_manager.UpdateDnsAuthorizationRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_dns_authorization._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_dns_authorization._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_dns_authorization(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_dns_authorization_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_dns_authorization._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "dnsAuthorization", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_dns_authorization_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_update_dns_authorization" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_update_dns_authorization" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.UpdateDnsAuthorizationRequest.pb( + certificate_manager.UpdateDnsAuthorizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.UpdateDnsAuthorizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_dns_authorization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_dns_authorization_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.UpdateDnsAuthorizationRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "dns_authorization": { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + } + request_init["dns_authorization"] = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "domain": "domain_value", + "dns_resource_record": { + "name": "name_value", + "type_": "type__value", + "data": "data_value", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_dns_authorization(request) + + +def test_update_dns_authorization_rest_flattened(): + client = CertificateManagerClient( + 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 = { + "dns_authorization": { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + dns_authorization=certificate_manager.DnsAuthorization(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_dns_authorization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{dns_authorization.name=projects/*/locations/*/dnsAuthorizations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_dns_authorization_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_dns_authorization( + certificate_manager.UpdateDnsAuthorizationRequest(), + dns_authorization=certificate_manager.DnsAuthorization(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_dns_authorization_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_manager.DeleteDnsAuthorizationRequest, + dict, + ], +) +def test_delete_dns_authorization_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_dns_authorization(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_dns_authorization_rest_required_fields( + request_type=certificate_manager.DeleteDnsAuthorizationRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_dns_authorization._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_dns_authorization._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 = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_dns_authorization(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_dns_authorization_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_dns_authorization._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_dns_authorization_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, "post_delete_dns_authorization" + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, "pre_delete_dns_authorization" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_manager.DeleteDnsAuthorizationRequest.pb( + certificate_manager.DeleteDnsAuthorizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_manager.DeleteDnsAuthorizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_dns_authorization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_dns_authorization_rest_bad_request( + transport: str = "rest", + request_type=certificate_manager.DeleteDnsAuthorizationRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dnsAuthorizations/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_dns_authorization(request) + + +def test_delete_dns_authorization_rest_flattened(): + client = CertificateManagerClient( + 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/dnsAuthorizations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_dns_authorization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/dnsAuthorizations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_dns_authorization_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_dns_authorization( + certificate_manager.DeleteDnsAuthorizationRequest(), + name="name_value", + ) + + +def test_delete_dns_authorization_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_issuance_config.ListCertificateIssuanceConfigsRequest, + dict, + ], +) +def test_list_certificate_issuance_configs_rest(request_type): + client = CertificateManagerClient( + 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 = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_issuance_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateIssuanceConfigsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_issuance_configs_rest_required_fields( + request_type=certificate_issuance_config.ListCertificateIssuanceConfigsRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_issuance_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_issuance_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_issuance_config.ListCertificateIssuanceConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_issuance_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_issuance_configs_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_certificate_issuance_configs._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_issuance_configs_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_list_certificate_issuance_configs", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, + "pre_list_certificate_issuance_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + certificate_issuance_config.ListCertificateIssuanceConfigsRequest.pb( + certificate_issuance_config.ListCertificateIssuanceConfigsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.to_json( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse() + ) + ) + + request = certificate_issuance_config.ListCertificateIssuanceConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse() + ) + + client.list_certificate_issuance_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_issuance_configs_rest_bad_request( + transport: str = "rest", + request_type=certificate_issuance_config.ListCertificateIssuanceConfigsRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_issuance_configs(request) + + +def test_list_certificate_issuance_configs_rest_flattened(): + client = CertificateManagerClient( + 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 = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_issuance_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateIssuanceConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_issuance_configs_rest_flattened_error( + transport: str = "rest", +): + client = CertificateManagerClient( + 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_certificate_issuance_configs( + certificate_issuance_config.ListCertificateIssuanceConfigsRequest(), + parent="parent_value", + ) + + +def test_list_certificate_issuance_configs_rest_pager(transport: str = "rest"): + client = CertificateManagerClient( + 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 = ( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse( + certificate_issuance_configs=[ + certificate_issuance_config.CertificateIssuanceConfig(), + certificate_issuance_config.CertificateIssuanceConfig(), + certificate_issuance_config.CertificateIssuanceConfig(), + ], + next_page_token="abc", + ), + certificate_issuance_config.ListCertificateIssuanceConfigsResponse( + certificate_issuance_configs=[], + next_page_token="def", + ), + certificate_issuance_config.ListCertificateIssuanceConfigsResponse( + certificate_issuance_configs=[ + certificate_issuance_config.CertificateIssuanceConfig(), + ], + next_page_token="ghi", + ), + certificate_issuance_config.ListCertificateIssuanceConfigsResponse( + certificate_issuance_configs=[ + certificate_issuance_config.CertificateIssuanceConfig(), + certificate_issuance_config.CertificateIssuanceConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + certificate_issuance_config.ListCertificateIssuanceConfigsResponse.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_certificate_issuance_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, certificate_issuance_config.CertificateIssuanceConfig) + for i in results + ) + + pages = list( + client.list_certificate_issuance_configs(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_issuance_config.GetCertificateIssuanceConfigRequest, + dict, + ], +) +def test_get_certificate_issuance_config_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateIssuanceConfigs/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 = certificate_issuance_config.CertificateIssuanceConfig( + name="name_value", + description="description_value", + rotation_window_percentage=2788, + key_algorithm=certificate_issuance_config.CertificateIssuanceConfig.KeyAlgorithm.RSA_2048, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_issuance_config.CertificateIssuanceConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_issuance_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate_issuance_config.CertificateIssuanceConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.rotation_window_percentage == 2788 + assert ( + response.key_algorithm + == certificate_issuance_config.CertificateIssuanceConfig.KeyAlgorithm.RSA_2048 + ) + + +def test_get_certificate_issuance_config_rest_required_fields( + request_type=certificate_issuance_config.GetCertificateIssuanceConfigRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_issuance_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_issuance_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = certificate_issuance_config.CertificateIssuanceConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = certificate_issuance_config.CertificateIssuanceConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_issuance_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_issuance_config_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_issuance_config._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_issuance_config_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_get_certificate_issuance_config", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, + "pre_get_certificate_issuance_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = certificate_issuance_config.GetCertificateIssuanceConfigRequest.pb( + certificate_issuance_config.GetCertificateIssuanceConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + certificate_issuance_config.CertificateIssuanceConfig.to_json( + certificate_issuance_config.CertificateIssuanceConfig() + ) + ) + + request = certificate_issuance_config.GetCertificateIssuanceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = certificate_issuance_config.CertificateIssuanceConfig() + + client.get_certificate_issuance_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_issuance_config_rest_bad_request( + transport: str = "rest", + request_type=certificate_issuance_config.GetCertificateIssuanceConfigRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateIssuanceConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_issuance_config(request) + + +def test_get_certificate_issuance_config_rest_flattened(): + client = CertificateManagerClient( + 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 = certificate_issuance_config.CertificateIssuanceConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateIssuanceConfigs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = certificate_issuance_config.CertificateIssuanceConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_issuance_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateIssuanceConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_issuance_config_rest_flattened_error(transport: str = "rest"): + client = CertificateManagerClient( + 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_certificate_issuance_config( + certificate_issuance_config.GetCertificateIssuanceConfigRequest(), + name="name_value", + ) + + +def test_get_certificate_issuance_config_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, + dict, + ], +) +def test_create_certificate_issuance_config_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_issuance_config"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "certificate_authority_config": { + "certificate_authority_service_config": {"ca_pool": "ca_pool_value"} + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "rotation_window_percentage": 2788, + "key_algorithm": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_issuance_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_issuance_config_rest_required_fields( + request_type=gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_issuance_config_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateIssuanceConfigId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_issuance_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateIssuanceConfigId" in jsonified_request + assert ( + jsonified_request["certificateIssuanceConfigId"] + == request_init["certificate_issuance_config_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request[ + "certificateIssuanceConfigId" + ] = "certificate_issuance_config_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_issuance_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("certificate_issuance_config_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "certificateIssuanceConfigId" in jsonified_request + assert ( + jsonified_request["certificateIssuanceConfigId"] + == "certificate_issuance_config_id_value" + ) + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_issuance_config(request) + + expected_params = [ + ( + "certificateIssuanceConfigId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_issuance_config_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_certificate_issuance_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("certificateIssuanceConfigId",)) + & set( + ( + "parent", + "certificateIssuanceConfigId", + "certificateIssuanceConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_issuance_config_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_create_certificate_issuance_config", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, + "pre_create_certificate_issuance_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest.pb( + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = ( + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_issuance_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_issuance_config_rest_bad_request( + transport: str = "rest", + request_type=gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_issuance_config"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "description": "description_value", + "certificate_authority_config": { + "certificate_authority_service_config": {"ca_pool": "ca_pool_value"} + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "rotation_window_percentage": 2788, + "key_algorithm": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_issuance_config(request) + + +def test_create_certificate_issuance_config_rest_flattened(): + client = CertificateManagerClient( + 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", + certificate_issuance_config=gcc_certificate_issuance_config.CertificateIssuanceConfig( + name="name_value" + ), + certificate_issuance_config_id="certificate_issuance_config_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_issuance_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateIssuanceConfigs" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_issuance_config_rest_flattened_error( + transport: str = "rest", +): + client = CertificateManagerClient( + 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_certificate_issuance_config( + gcc_certificate_issuance_config.CreateCertificateIssuanceConfigRequest(), + parent="parent_value", + certificate_issuance_config=gcc_certificate_issuance_config.CertificateIssuanceConfig( + name="name_value" + ), + certificate_issuance_config_id="certificate_issuance_config_id_value", + ) + + +def test_create_certificate_issuance_config_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, + dict, + ], +) +def test_delete_certificate_issuance_config_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateIssuanceConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_issuance_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_issuance_config_rest_required_fields( + request_type=certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, +): + transport_class = transports.CertificateManagerRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_issuance_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_issuance_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate_issuance_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_issuance_config_rest_unset_required_fields(): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_certificate_issuance_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_issuance_config_rest_interceptors(null_interceptor): + transport = transports.CertificateManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateManagerRestInterceptor(), + ) + client = CertificateManagerClient(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.CertificateManagerRestInterceptor, + "post_delete_certificate_issuance_config", + ) as post, mock.patch.object( + transports.CertificateManagerRestInterceptor, + "pre_delete_certificate_issuance_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest.pb( + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = certificate_issuance_config.DeleteCertificateIssuanceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_issuance_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_issuance_config_rest_bad_request( + transport: str = "rest", + request_type=certificate_issuance_config.DeleteCertificateIssuanceConfigRequest, +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateIssuanceConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate_issuance_config(request) + + +def test_delete_certificate_issuance_config_rest_flattened(): + client = CertificateManagerClient( + 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/certificateIssuanceConfigs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate_issuance_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateIssuanceConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_issuance_config_rest_flattened_error( + transport: str = "rest", +): + client = CertificateManagerClient( + 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_certificate_issuance_config( + certificate_issuance_config.DeleteCertificateIssuanceConfigRequest(), + name="name_value", + ) + + +def test_delete_certificate_issuance_config_rest_error(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateManagerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateManagerClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateManagerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CertificateManagerClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CertificateManagerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateManagerGrpcTransport, + transports.CertificateManagerGrpcAsyncIOTransport, + transports.CertificateManagerRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CertificateManagerClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CertificateManagerGrpcTransport, + ) + + +def test_certificate_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CertificateManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_certificate_manager_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.certificate_manager_v1.services.certificate_manager.transports.CertificateManagerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CertificateManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "list_certificates", @@ -8085,6 +15655,7 @@ def test_certificate_manager_transport_auth_adc(transport_class): [ transports.CertificateManagerGrpcTransport, transports.CertificateManagerGrpcAsyncIOTransport, + transports.CertificateManagerRestTransport, ], ) def test_certificate_manager_transport_auth_gdch_credentials(transport_class): @@ -8184,11 +15755,40 @@ def test_certificate_manager_grpc_transport_client_cert_source_for_mtls( ) +def test_certificate_manager_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.CertificateManagerRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_certificate_manager_rest_lro_client(): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_certificate_manager_host_no_port(transport_name): @@ -8199,7 +15799,11 @@ def test_certificate_manager_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("certificatemanager.googleapis.com:443") + assert client.transport._host == ( + "certificatemanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://certificatemanager.googleapis.com" + ) @pytest.mark.parametrize( @@ -8207,6 +15811,7 @@ def test_certificate_manager_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_certificate_manager_host_with_port(transport_name): @@ -8217,7 +15822,102 @@ def test_certificate_manager_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("certificatemanager.googleapis.com:8000") + assert client.transport._host == ( + "certificatemanager.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://certificatemanager.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_certificate_manager_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CertificateManagerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CertificateManagerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_certificates._session + session2 = client2.transport.list_certificates._session + assert session1 != session2 + session1 = client1.transport.get_certificate._session + session2 = client2.transport.get_certificate._session + assert session1 != session2 + session1 = client1.transport.create_certificate._session + session2 = client2.transport.create_certificate._session + assert session1 != session2 + session1 = client1.transport.update_certificate._session + session2 = client2.transport.update_certificate._session + assert session1 != session2 + session1 = client1.transport.delete_certificate._session + session2 = client2.transport.delete_certificate._session + assert session1 != session2 + session1 = client1.transport.list_certificate_maps._session + session2 = client2.transport.list_certificate_maps._session + assert session1 != session2 + session1 = client1.transport.get_certificate_map._session + session2 = client2.transport.get_certificate_map._session + assert session1 != session2 + session1 = client1.transport.create_certificate_map._session + session2 = client2.transport.create_certificate_map._session + assert session1 != session2 + session1 = client1.transport.update_certificate_map._session + session2 = client2.transport.update_certificate_map._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_map._session + session2 = client2.transport.delete_certificate_map._session + assert session1 != session2 + session1 = client1.transport.list_certificate_map_entries._session + session2 = client2.transport.list_certificate_map_entries._session + assert session1 != session2 + session1 = client1.transport.get_certificate_map_entry._session + session2 = client2.transport.get_certificate_map_entry._session + assert session1 != session2 + session1 = client1.transport.create_certificate_map_entry._session + session2 = client2.transport.create_certificate_map_entry._session + assert session1 != session2 + session1 = client1.transport.update_certificate_map_entry._session + session2 = client2.transport.update_certificate_map_entry._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_map_entry._session + session2 = client2.transport.delete_certificate_map_entry._session + assert session1 != session2 + session1 = client1.transport.list_dns_authorizations._session + session2 = client2.transport.list_dns_authorizations._session + assert session1 != session2 + session1 = client1.transport.get_dns_authorization._session + session2 = client2.transport.get_dns_authorization._session + assert session1 != session2 + session1 = client1.transport.create_dns_authorization._session + session2 = client2.transport.create_dns_authorization._session + assert session1 != session2 + session1 = client1.transport.update_dns_authorization._session + session2 = client2.transport.update_dns_authorization._session + assert session1 != session2 + session1 = client1.transport.delete_dns_authorization._session + session2 = client2.transport.delete_dns_authorization._session + assert session1 != session2 + session1 = client1.transport.list_certificate_issuance_configs._session + session2 = client2.transport.list_certificate_issuance_configs._session + assert session1 != session2 + session1 = client1.transport.get_certificate_issuance_config._session + session2 = client2.transport.get_certificate_issuance_config._session + assert session1 != session2 + session1 = client1.transport.create_certificate_issuance_config._session + session2 = client2.transport.create_certificate_issuance_config._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_issuance_config._session + session2 = client2.transport.delete_certificate_issuance_config._session + assert session1 != session2 def test_certificate_manager_grpc_transport_channel(): @@ -8689,6 +16389,352 @@ async def test_transport_close_async(): close.assert_called_once() +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CertificateManagerClient( + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CertificateManagerClient( + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = CertificateManagerClient( + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + 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( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CertificateManagerClient( + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = CertificateManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CertificateManagerClient( + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + def test_delete_operation(transport: str = "grpc"): client = CertificateManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9547,6 +17593,7 @@ async def test_get_location_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -9564,6 +17611,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: