diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json index 3b8309798b68..00dfdf5ad83c 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json @@ -56,6 +56,31 @@ ] } } + }, + "rest": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } } } }, @@ -330,6 +355,141 @@ ] } } + }, + "rest": { + "libraryClient": "KeyManagementServiceClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } } } } diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/async_client.py index 933889f048bf..e7a166a8fc3a 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/async_client.py @@ -42,6 +42,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore @@ -755,6 +756,114 @@ async def sample_update_ekm_connection(): # Done; return the response. return response + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def set_iam_policy( self, request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/client.py index 1065bb846d4b..08f9da61ee34 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore @@ -57,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, EkmServiceTransport from .transports.grpc import EkmServiceGrpcTransport from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .transports.rest import EkmServiceRestTransport class EkmServiceClientMeta(type): @@ -70,6 +72,7 @@ class EkmServiceClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] _transport_registry["grpc"] = EkmServiceGrpcTransport _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EkmServiceRestTransport def get_transport_class( cls, @@ -981,6 +984,114 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def set_iam_policy( self, request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/__init__.py index 06053977c6ca..16af736610e4 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import EkmServiceTransport from .grpc import EkmServiceGrpcTransport from .grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .rest import EkmServiceRestInterceptor, EkmServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] _transport_registry["grpc"] = EkmServiceGrpcTransport _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EkmServiceRestTransport __all__ = ( "EkmServiceTransport", "EkmServiceGrpcTransport", "EkmServiceGrpcAsyncIOTransport", + "EkmServiceRestTransport", + "EkmServiceRestInterceptor", ) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/base.py index 9f95547fd8ce..1c03a48580b7 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/base.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/base.py @@ -22,6 +22,7 @@ from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account # type: ignore @@ -237,6 +238,27 @@ def update_ekm_connection( ]: raise NotImplementedError() + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + @property def set_iam_policy( self, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc.py index 7baa20ca7c89..b94addead59a 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc.py @@ -20,6 +20,7 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore import grpc # type: ignore @@ -427,6 +428,42 @@ def test_iam_permissions( def close(self): self.grpc_channel.close() + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py index d4a4932fab27..54030e4d1658 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py @@ -19,6 +19,7 @@ from google.api_core import gapic_v1, grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore import grpc # type: ignore @@ -437,5 +438,41 @@ def test_iam_permissions( def close(self): return self.grpc_channel.close() + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + __all__ = ("EkmServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/rest.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/rest.py new file mode 100644 index 000000000000..0c0a875f86bf --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/ekm_service/transports/rest.py @@ -0,0 +1,1280 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +from google.cloud.kms_v1.types import ekm_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import EkmServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class EkmServiceRestInterceptor: + """Interceptor for EkmService. + + 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 EkmServiceRestTransport. + + .. code-block:: python + class MyCustomEkmServiceInterceptor(EkmServiceRestInterceptor): + def pre_create_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ekm_connections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ekm_connections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EkmServiceRestTransport(interceptor=MyCustomEkmServiceInterceptor()) + client = EkmServiceClient(transport=transport) + + + """ + + def pre_create_ekm_connection( + self, + request: ekm_service.CreateEkmConnectionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_service.CreateEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_create_ekm_connection( + self, response: ekm_service.EkmConnection + ) -> ekm_service.EkmConnection: + """Post-rpc interceptor for create_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_ekm_connection( + self, + request: ekm_service.GetEkmConnectionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_service.GetEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_ekm_connection( + self, response: ekm_service.EkmConnection + ) -> ekm_service.EkmConnection: + """Post-rpc interceptor for get_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_list_ekm_connections( + self, + request: ekm_service.ListEkmConnectionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_service.ListEkmConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_ekm_connections + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_list_ekm_connections( + self, response: ekm_service.ListEkmConnectionsResponse + ) -> ekm_service.ListEkmConnectionsResponse: + """Post-rpc interceptor for list_ekm_connections + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_update_ekm_connection( + self, + request: ekm_service.UpdateEkmConnectionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_service.UpdateEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_update_ekm_connection( + self, response: ekm_service.EkmConnection + ) -> ekm_service.EkmConnection: + """Post-rpc interceptor for update_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService 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 EkmService 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 EkmService 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 EkmService 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 EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: iam_policy_pb2.GetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: iam_policy_pb2.SetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsRequest + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EkmServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EkmServiceRestInterceptor + + +class EkmServiceRestTransport(EkmServiceTransport): + """REST backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 = "cloudkms.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[EkmServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EkmServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateEkmConnection(EkmServiceRestStub): + def __hash__(self): + return hash("CreateEkmConnection") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "ekmConnectionId": "", + } + + @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: ekm_service.CreateEkmConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Call the create ekm connection method over HTTP. + + Args: + request (~.ekm_service.CreateEkmConnectionRequest): + The request object. Request message for + [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. + + 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: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/ekmConnections", + "body": "ekm_connection", + }, + ] + request, metadata = self._interceptor.pre_create_ekm_connection( + request, metadata + ) + pb_request = ekm_service.CreateEkmConnectionRequest.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 = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_ekm_connection(resp) + return resp + + class _GetEkmConnection(EkmServiceRestStub): + def __hash__(self): + return hash("GetEkmConnection") + + __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: ekm_service.GetEkmConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Call the get ekm connection method over HTTP. + + Args: + request (~.ekm_service.GetEkmConnectionRequest): + The request object. Request message for + [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. + + 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: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/ekmConnections/*}", + }, + ] + request, metadata = self._interceptor.pre_get_ekm_connection( + request, metadata + ) + pb_request = ekm_service.GetEkmConnectionRequest.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 = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ekm_connection(resp) + return resp + + class _ListEkmConnections(EkmServiceRestStub): + def __hash__(self): + return hash("ListEkmConnections") + + __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: ekm_service.ListEkmConnectionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.ListEkmConnectionsResponse: + r"""Call the list ekm connections method over HTTP. + + Args: + request (~.ekm_service.ListEkmConnectionsRequest): + The request object. Request message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + 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: + ~.ekm_service.ListEkmConnectionsResponse: + Response message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/ekmConnections", + }, + ] + request, metadata = self._interceptor.pre_list_ekm_connections( + request, metadata + ) + pb_request = ekm_service.ListEkmConnectionsRequest.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 = ekm_service.ListEkmConnectionsResponse() + pb_resp = ekm_service.ListEkmConnectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_ekm_connections(resp) + return resp + + class _UpdateEkmConnection(EkmServiceRestStub): + def __hash__(self): + return hash("UpdateEkmConnection") + + __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: ekm_service.UpdateEkmConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Call the update ekm connection method over HTTP. + + Args: + request (~.ekm_service.UpdateEkmConnectionRequest): + The request object. Request message for + [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. + + 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: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}", + "body": "ekm_connection", + }, + ] + request, metadata = self._interceptor.pre_update_ekm_connection( + request, metadata + ) + pb_request = ekm_service.UpdateEkmConnectionRequest.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 = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_ekm_connection(resp) + return resp + + @property + def create_ekm_connection( + self, + ) -> Callable[[ekm_service.CreateEkmConnectionRequest], ekm_service.EkmConnection]: + # 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._CreateEkmConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ekm_connection( + self, + ) -> Callable[[ekm_service.GetEkmConnectionRequest], ekm_service.EkmConnection]: + # 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._GetEkmConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], ekm_service.ListEkmConnectionsResponse + ]: + # 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._ListEkmConnections(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ekm_connection( + self, + ) -> Callable[[ekm_service.UpdateEkmConnectionRequest], ekm_service.EkmConnection]: + # 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._UpdateEkmConnection(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(EkmServiceRestStub): + 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(EkmServiceRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(EkmServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(EkmServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(EkmServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("EkmServiceRestTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py index befe81e71e86..799793963db5 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -42,6 +42,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import duration_pb2 # type: ignore @@ -3747,6 +3748,114 @@ async def sample_generate_random_bytes(): # Done; return the response. return response + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def set_iam_policy( self, request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index deab2844a2b1..de4214b63543 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import duration_pb2 # type: ignore @@ -59,6 +60,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, KeyManagementServiceTransport from .transports.grpc import KeyManagementServiceGrpcTransport from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .transports.rest import KeyManagementServiceRestTransport class KeyManagementServiceClientMeta(type): @@ -74,6 +76,7 @@ class KeyManagementServiceClientMeta(type): ) # type: Dict[str, Type[KeyManagementServiceTransport]] _transport_registry["grpc"] = KeyManagementServiceGrpcTransport _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport + _transport_registry["rest"] = KeyManagementServiceRestTransport def get_transport_class( cls, @@ -3841,6 +3844,114 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def set_iam_policy( self, request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/__init__.py index 46fb60193b58..c4d5f2f9b98c 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/__init__.py @@ -19,6 +19,7 @@ from .base import KeyManagementServiceTransport from .grpc import KeyManagementServiceGrpcTransport from .grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .rest import KeyManagementServiceRestInterceptor, KeyManagementServiceRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[KeyManagementServiceTransport]] _transport_registry["grpc"] = KeyManagementServiceGrpcTransport _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport +_transport_registry["rest"] = KeyManagementServiceRestTransport __all__ = ( "KeyManagementServiceTransport", "KeyManagementServiceGrpcTransport", "KeyManagementServiceGrpcAsyncIOTransport", + "KeyManagementServiceRestTransport", + "KeyManagementServiceRestInterceptor", ) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py index d514677e150a..ade762ef7d94 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -22,6 +22,7 @@ from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account # type: ignore @@ -757,6 +758,27 @@ def generate_random_bytes( ]: raise NotImplementedError() + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + @property def set_iam_policy( self, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index a03566d18635..54793ad1945a 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -20,6 +20,7 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore import grpc # type: ignore @@ -1118,6 +1119,42 @@ def test_iam_permissions( def close(self): self.grpc_channel.close() + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index da343d08c3be..bb4249250cc1 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -19,6 +19,7 @@ from google.api_core import gapic_v1, grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore import grpc # type: ignore @@ -1153,5 +1154,41 @@ def test_iam_permissions( def close(self): return self.grpc_channel.close() + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + __all__ = ("KeyManagementServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py new file mode 100644 index 000000000000..677b59ca3f8b --- /dev/null +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py @@ -0,0 +1,4411 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +from google.cloud.kms_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import KeyManagementServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class KeyManagementServiceRestInterceptor: + """Interceptor for KeyManagementService. + + 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 KeyManagementServiceRestTransport. + + .. code-block:: python + class MyCustomKeyManagementServiceInterceptor(KeyManagementServiceRestInterceptor): + def pre_asymmetric_decrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_asymmetric_decrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_asymmetric_sign(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_asymmetric_sign(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_import_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_import_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_key_ring(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_ring(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_decrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_decrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_destroy_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_destroy_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_encrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_encrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_random_bytes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_random_bytes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_import_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_import_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_key_ring(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_ring(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_public_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_public_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crypto_keys(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crypto_keys(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crypto_key_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crypto_key_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_import_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_import_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_key_rings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_rings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mac_sign(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mac_sign(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mac_verify(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mac_verify(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key_primary_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key_primary_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + transport = KeyManagementServiceRestTransport(interceptor=MyCustomKeyManagementServiceInterceptor()) + client = KeyManagementServiceClient(transport=transport) + + + """ + + def pre_asymmetric_decrypt( + self, + request: service.AsymmetricDecryptRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.AsymmetricDecryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for asymmetric_decrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_asymmetric_decrypt( + self, response: service.AsymmetricDecryptResponse + ) -> service.AsymmetricDecryptResponse: + """Post-rpc interceptor for asymmetric_decrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_asymmetric_sign( + self, + request: service.AsymmetricSignRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.AsymmetricSignRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for asymmetric_sign + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_asymmetric_sign( + self, response: service.AsymmetricSignResponse + ) -> service.AsymmetricSignResponse: + """Post-rpc interceptor for asymmetric_sign + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_crypto_key( + self, + request: service.CreateCryptoKeyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_crypto_key( + self, response: resources.CryptoKey + ) -> resources.CryptoKey: + """Post-rpc interceptor for create_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_crypto_key_version( + self, + request: service.CreateCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for create_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_import_job( + self, + request: service.CreateImportJobRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateImportJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_import_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_import_job( + self, response: resources.ImportJob + ) -> resources.ImportJob: + """Post-rpc interceptor for create_import_job + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_key_ring( + self, request: service.CreateKeyRingRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.CreateKeyRingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_ring + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: + """Post-rpc interceptor for create_key_ring + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_decrypt( + self, request: service.DecryptRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.DecryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for decrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_decrypt( + self, response: service.DecryptResponse + ) -> service.DecryptResponse: + """Post-rpc interceptor for decrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_destroy_crypto_key_version( + self, + request: service.DestroyCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DestroyCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for destroy_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_destroy_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for destroy_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_encrypt( + self, request: service.EncryptRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.EncryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for encrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_encrypt( + self, response: service.EncryptResponse + ) -> service.EncryptResponse: + """Post-rpc interceptor for encrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_generate_random_bytes( + self, + request: service.GenerateRandomBytesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GenerateRandomBytesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_random_bytes + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_generate_random_bytes( + self, response: service.GenerateRandomBytesResponse + ) -> service.GenerateRandomBytesResponse: + """Post-rpc interceptor for generate_random_bytes + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_crypto_key( + self, request: service.GetCryptoKeyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: + """Post-rpc interceptor for get_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_crypto_key_version( + self, + request: service.GetCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for get_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_import_job( + self, request: service.GetImportJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetImportJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_import_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_import_job(self, response: resources.ImportJob) -> resources.ImportJob: + """Post-rpc interceptor for get_import_job + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_key_ring( + self, request: service.GetKeyRingRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetKeyRingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_ring + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: + """Post-rpc interceptor for get_key_ring + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_public_key( + self, request: service.GetPublicKeyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetPublicKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_public_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_public_key(self, response: resources.PublicKey) -> resources.PublicKey: + """Post-rpc interceptor for get_public_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_import_crypto_key_version( + self, + request: service.ImportCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ImportCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_import_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for import_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_crypto_keys( + self, + request: service.ListCryptoKeysRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCryptoKeysRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crypto_keys + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_crypto_keys( + self, response: service.ListCryptoKeysResponse + ) -> service.ListCryptoKeysResponse: + """Post-rpc interceptor for list_crypto_keys + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_crypto_key_versions( + self, + request: service.ListCryptoKeyVersionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCryptoKeyVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crypto_key_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_crypto_key_versions( + self, response: service.ListCryptoKeyVersionsResponse + ) -> service.ListCryptoKeyVersionsResponse: + """Post-rpc interceptor for list_crypto_key_versions + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_import_jobs( + self, + request: service.ListImportJobsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListImportJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_import_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_import_jobs( + self, response: service.ListImportJobsResponse + ) -> service.ListImportJobsResponse: + """Post-rpc interceptor for list_import_jobs + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_key_rings( + self, request: service.ListKeyRingsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListKeyRingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_rings + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_key_rings( + self, response: service.ListKeyRingsResponse + ) -> service.ListKeyRingsResponse: + """Post-rpc interceptor for list_key_rings + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_mac_sign( + self, request: service.MacSignRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.MacSignRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for mac_sign + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_mac_sign( + self, response: service.MacSignResponse + ) -> service.MacSignResponse: + """Post-rpc interceptor for mac_sign + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_mac_verify( + self, request: service.MacVerifyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.MacVerifyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for mac_verify + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_mac_verify( + self, response: service.MacVerifyResponse + ) -> service.MacVerifyResponse: + """Post-rpc interceptor for mac_verify + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_restore_crypto_key_version( + self, + request: service.RestoreCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.RestoreCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_restore_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for restore_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key( + self, + request: service.UpdateCryptoKeyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key( + self, response: resources.CryptoKey + ) -> resources.CryptoKey: + """Post-rpc interceptor for update_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key_primary_version( + self, + request: service.UpdateCryptoKeyPrimaryVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCryptoKeyPrimaryVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key_primary_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key_primary_version( + self, response: resources.CryptoKey + ) -> resources.CryptoKey: + """Post-rpc interceptor for update_crypto_key_primary_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key_version( + self, + request: service.UpdateCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for update_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService 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 KeyManagementService 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 KeyManagementService 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 KeyManagementService 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 KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: iam_policy_pb2.GetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> policy_pb2.Policy: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: iam_policy_pb2.SetIamPolicyRequest + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsRequest + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class KeyManagementServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: KeyManagementServiceRestInterceptor + + +class KeyManagementServiceRestTransport(KeyManagementServiceTransport): + """REST backend transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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 = "cloudkms.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[KeyManagementServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or KeyManagementServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AsymmetricDecrypt(KeyManagementServiceRestStub): + def __hash__(self): + return hash("AsymmetricDecrypt") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.AsymmetricDecryptRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricDecryptResponse: + r"""Call the asymmetric decrypt method over HTTP. + + Args: + request (~.service.AsymmetricDecryptRequest): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_asymmetric_decrypt( + request, metadata + ) + pb_request = service.AsymmetricDecryptRequest.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 = service.AsymmetricDecryptResponse() + pb_resp = service.AsymmetricDecryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_asymmetric_decrypt(resp) + return resp + + class _AsymmetricSign(KeyManagementServiceRestStub): + def __hash__(self): + return hash("AsymmetricSign") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.AsymmetricSignRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricSignResponse: + r"""Call the asymmetric sign method over HTTP. + + Args: + request (~.service.AsymmetricSignRequest): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_asymmetric_sign(request, metadata) + pb_request = service.AsymmetricSignRequest.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 = service.AsymmetricSignResponse() + pb_resp = service.AsymmetricSignResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_asymmetric_sign(resp) + return resp + + class _CreateCryptoKey(KeyManagementServiceRestStub): + def __hash__(self): + return hash("CreateCryptoKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "cryptoKeyId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCryptoKeyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Call the create crypto key method over HTTP. + + Args: + request (~.service.CreateCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + + 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: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys", + "body": "crypto_key", + }, + ] + request, metadata = self._interceptor.pre_create_crypto_key( + request, metadata + ) + pb_request = service.CreateCryptoKeyRequest.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 = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_crypto_key(resp) + return resp + + class _CreateCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("CreateCryptoKeyVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the create crypto key version method over HTTP. + + Args: + request (~.service.CreateCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions", + "body": "crypto_key_version", + }, + ] + request, metadata = self._interceptor.pre_create_crypto_key_version( + request, metadata + ) + pb_request = service.CreateCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_crypto_key_version(resp) + return resp + + class _CreateImportJob(KeyManagementServiceRestStub): + def __hash__(self): + return hash("CreateImportJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "importJobId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateImportJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Call the create import job method over HTTP. + + Args: + request (~.service.CreateImportJobRequest): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + + 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: + ~.resources.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be + used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", which + is a public/private key pair. You use the wrapping key + to encrypt (also known as wrap) the pre-existing key + material to protect it during the import process. The + nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set + to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be used + to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 + days after it is created. Once expired, Cloud KMS will + no longer be able to import or unwrap any key material + that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs", + "body": "import_job", + }, + ] + request, metadata = self._interceptor.pre_create_import_job( + request, metadata + ) + pb_request = service.CreateImportJobRequest.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 = resources.ImportJob() + pb_resp = resources.ImportJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_import_job(resp) + return resp + + class _CreateKeyRing(KeyManagementServiceRestStub): + def __hash__(self): + return hash("CreateKeyRing") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "keyRingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateKeyRingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Call the create key ring method over HTTP. + + Args: + request (~.service.CreateKeyRingRequest): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + + 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: + ~.resources.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel + logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/keyRings", + "body": "key_ring", + }, + ] + request, metadata = self._interceptor.pre_create_key_ring(request, metadata) + pb_request = service.CreateKeyRingRequest.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 = resources.KeyRing() + pb_resp = resources.KeyRing.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_key_ring(resp) + return resp + + class _Decrypt(KeyManagementServiceRestStub): + def __hash__(self): + return hash("Decrypt") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DecryptRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.DecryptResponse: + r"""Call the decrypt method over HTTP. + + Args: + request (~.service.DecryptRequest): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:decrypt", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_decrypt(request, metadata) + pb_request = service.DecryptRequest.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 = service.DecryptResponse() + pb_resp = service.DecryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_decrypt(resp) + return resp + + class _DestroyCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("DestroyCryptoKeyVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DestroyCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the destroy crypto key + version method over HTTP. + + Args: + request (~.service.DestroyCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_destroy_crypto_key_version( + request, metadata + ) + pb_request = service.DestroyCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_destroy_crypto_key_version(resp) + return resp + + class _Encrypt(KeyManagementServiceRestStub): + def __hash__(self): + return hash("Encrypt") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.EncryptRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.EncryptResponse: + r"""Call the encrypt method over HTTP. + + Args: + request (~.service.EncryptRequest): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/**}:encrypt", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_encrypt(request, metadata) + pb_request = service.EncryptRequest.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 = service.EncryptResponse() + pb_resp = service.EncryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_encrypt(resp) + return resp + + class _GenerateRandomBytes(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GenerateRandomBytes") + + def __call__( + self, + request: service.GenerateRandomBytesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateRandomBytesResponse: + r"""Call the generate random bytes method over HTTP. + + Args: + request (~.service.GenerateRandomBytesRequest): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{location=projects/*/locations/*}:generateRandomBytes", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_generate_random_bytes( + request, metadata + ) + pb_request = service.GenerateRandomBytesRequest.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["$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 = service.GenerateRandomBytesResponse() + pb_resp = service.GenerateRandomBytesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_random_bytes(resp) + return resp + + class _GetCryptoKey(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GetCryptoKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCryptoKeyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Call the get crypto key method over HTTP. + + Args: + request (~.service.GetCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + + 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: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}", + }, + ] + request, metadata = self._interceptor.pre_get_crypto_key(request, metadata) + pb_request = service.GetCryptoKeyRequest.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 = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_crypto_key(resp) + return resp + + class _GetCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GetCryptoKeyVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the get crypto key version method over HTTP. + + Args: + request (~.service.GetCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}", + }, + ] + request, metadata = self._interceptor.pre_get_crypto_key_version( + request, metadata + ) + pb_request = service.GetCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_crypto_key_version(resp) + return resp + + class _GetImportJob(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GetImportJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetImportJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Call the get import job method over HTTP. + + Args: + request (~.service.GetImportJobRequest): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + + 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: + ~.resources.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be + used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", which + is a public/private key pair. You use the wrapping key + to encrypt (also known as wrap) the pre-existing key + material to protect it during the import process. The + nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set + to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be used + to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 + days after it is created. Once expired, Cloud KMS will + no longer be able to import or unwrap any key material + that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/importJobs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_import_job(request, metadata) + pb_request = service.GetImportJobRequest.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 = resources.ImportJob() + pb_resp = resources.ImportJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_import_job(resp) + return resp + + class _GetKeyRing(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GetKeyRing") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetKeyRingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Call the get key ring method over HTTP. + + Args: + request (~.service.GetKeyRingRequest): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + + 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: + ~.resources.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel + logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*}", + }, + ] + request, metadata = self._interceptor.pre_get_key_ring(request, metadata) + pb_request = service.GetKeyRingRequest.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 = resources.KeyRing() + pb_resp = resources.KeyRing.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_key_ring(resp) + return resp + + class _GetPublicKey(KeyManagementServiceRestStub): + def __hash__(self): + return hash("GetPublicKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetPublicKeyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.PublicKey: + r"""Call the get public key method over HTTP. + + Args: + request (~.service.GetPublicKeyRequest): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + 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: + ~.resources.PublicKey: + The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey", + }, + ] + request, metadata = self._interceptor.pre_get_public_key(request, metadata) + pb_request = service.GetPublicKeyRequest.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 = resources.PublicKey() + pb_resp = resources.PublicKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_public_key(resp) + return resp + + class _ImportCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("ImportCryptoKeyVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ImportCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the import crypto key version method over HTTP. + + Args: + request (~.service.ImportCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions:import", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_import_crypto_key_version( + request, metadata + ) + pb_request = service.ImportCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_crypto_key_version(resp) + return resp + + class _ListCryptoKeys(KeyManagementServiceRestStub): + def __hash__(self): + return hash("ListCryptoKeys") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCryptoKeysRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCryptoKeysResponse: + r"""Call the list crypto keys method over HTTP. + + Args: + request (~.service.ListCryptoKeysRequest): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCryptoKeysResponse: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys", + }, + ] + request, metadata = self._interceptor.pre_list_crypto_keys( + request, metadata + ) + pb_request = service.ListCryptoKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCryptoKeysResponse() + pb_resp = service.ListCryptoKeysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crypto_keys(resp) + return resp + + class _ListCryptoKeyVersions(KeyManagementServiceRestStub): + def __hash__(self): + return hash("ListCryptoKeyVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCryptoKeyVersionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCryptoKeyVersionsResponse: + r"""Call the list crypto key versions method over HTTP. + + Args: + request (~.service.ListCryptoKeyVersionsRequest): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCryptoKeyVersionsResponse: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions", + }, + ] + request, metadata = self._interceptor.pre_list_crypto_key_versions( + request, metadata + ) + pb_request = service.ListCryptoKeyVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCryptoKeyVersionsResponse() + pb_resp = service.ListCryptoKeyVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crypto_key_versions(resp) + return resp + + class _ListImportJobs(KeyManagementServiceRestStub): + def __hash__(self): + return hash("ListImportJobs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListImportJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListImportJobsResponse: + r"""Call the list import jobs method over HTTP. + + Args: + request (~.service.ListImportJobsRequest): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListImportJobsResponse: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs", + }, + ] + request, metadata = self._interceptor.pre_list_import_jobs( + request, metadata + ) + pb_request = service.ListImportJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListImportJobsResponse() + pb_resp = service.ListImportJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_import_jobs(resp) + return resp + + class _ListKeyRings(KeyManagementServiceRestStub): + def __hash__(self): + return hash("ListKeyRings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListKeyRingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListKeyRingsResponse: + r"""Call the list key rings method over HTTP. + + Args: + request (~.service.ListKeyRingsRequest): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListKeyRingsResponse: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/keyRings", + }, + ] + request, metadata = self._interceptor.pre_list_key_rings(request, metadata) + pb_request = service.ListKeyRingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListKeyRingsResponse() + pb_resp = service.ListKeyRingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_rings(resp) + return resp + + class _MacSign(KeyManagementServiceRestStub): + def __hash__(self): + return hash("MacSign") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.MacSignRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacSignResponse: + r"""Call the mac sign method over HTTP. + + Args: + request (~.service.MacSignRequest): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_mac_sign(request, metadata) + pb_request = service.MacSignRequest.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 = service.MacSignResponse() + pb_resp = service.MacSignResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_mac_sign(resp) + return resp + + class _MacVerify(KeyManagementServiceRestStub): + def __hash__(self): + return hash("MacVerify") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.MacVerifyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacVerifyResponse: + r"""Call the mac verify method over HTTP. + + Args: + request (~.service.MacVerifyRequest): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_mac_verify(request, metadata) + pb_request = service.MacVerifyRequest.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 = service.MacVerifyResponse() + pb_resp = service.MacVerifyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_mac_verify(resp) + return resp + + class _RestoreCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("RestoreCryptoKeyVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.RestoreCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the restore crypto key + version method over HTTP. + + Args: + request (~.service.RestoreCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_restore_crypto_key_version( + request, metadata + ) + pb_request = service.RestoreCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_crypto_key_version(resp) + return resp + + class _UpdateCryptoKey(KeyManagementServiceRestStub): + def __hash__(self): + return hash("UpdateCryptoKey") + + __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: service.UpdateCryptoKeyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Call the update crypto key method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + + 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: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}", + "body": "crypto_key", + }, + ] + request, metadata = self._interceptor.pre_update_crypto_key( + request, metadata + ) + pb_request = service.UpdateCryptoKeyRequest.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 = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key(resp) + return resp + + class _UpdateCryptoKeyPrimaryVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("UpdateCryptoKeyPrimaryVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCryptoKeyPrimaryVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Call the update crypto key primary + version method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyPrimaryVersionRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + + 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: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_update_crypto_key_primary_version( + request, metadata + ) + pb_request = service.UpdateCryptoKeyPrimaryVersionRequest.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 = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key_primary_version(resp) + return resp + + class _UpdateCryptoKeyVersion(KeyManagementServiceRestStub): + def __hash__(self): + return hash("UpdateCryptoKeyVersion") + + __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: service.UpdateCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the update crypto key version method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}", + "body": "crypto_key_version", + }, + ] + request, metadata = self._interceptor.pre_update_crypto_key_version( + request, metadata + ) + pb_request = service.UpdateCryptoKeyVersionRequest.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 = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key_version(resp) + return resp + + @property + def asymmetric_decrypt( + self, + ) -> Callable[ + [service.AsymmetricDecryptRequest], service.AsymmetricDecryptResponse + ]: + # 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._AsymmetricDecrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def asymmetric_sign( + self, + ) -> Callable[[service.AsymmetricSignRequest], service.AsymmetricSignResponse]: + # 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._AsymmetricSign(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_crypto_key( + self, + ) -> Callable[[service.CreateCryptoKeyRequest], resources.CryptoKey]: + # 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._CreateCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_crypto_key_version( + self, + ) -> Callable[[service.CreateCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._CreateCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_import_job( + self, + ) -> Callable[[service.CreateImportJobRequest], resources.ImportJob]: + # 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._CreateImportJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_key_ring( + self, + ) -> Callable[[service.CreateKeyRingRequest], resources.KeyRing]: + # 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._CreateKeyRing(self._session, self._host, self._interceptor) # type: ignore + + @property + def decrypt(self) -> Callable[[service.DecryptRequest], service.DecryptResponse]: + # 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._Decrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def destroy_crypto_key_version( + self, + ) -> Callable[[service.DestroyCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._DestroyCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def encrypt(self) -> Callable[[service.EncryptRequest], service.EncryptResponse]: + # 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._Encrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_random_bytes( + self, + ) -> Callable[ + [service.GenerateRandomBytesRequest], service.GenerateRandomBytesResponse + ]: + # 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._GenerateRandomBytes(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_crypto_key( + self, + ) -> Callable[[service.GetCryptoKeyRequest], resources.CryptoKey]: + # 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._GetCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_crypto_key_version( + self, + ) -> Callable[[service.GetCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._GetCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_import_job( + self, + ) -> Callable[[service.GetImportJobRequest], resources.ImportJob]: + # 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._GetImportJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_key_ring(self) -> Callable[[service.GetKeyRingRequest], resources.KeyRing]: + # 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._GetKeyRing(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_public_key( + self, + ) -> Callable[[service.GetPublicKeyRequest], resources.PublicKey]: + # 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._GetPublicKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_crypto_key_version( + self, + ) -> Callable[[service.ImportCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._ImportCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crypto_keys( + self, + ) -> Callable[[service.ListCryptoKeysRequest], service.ListCryptoKeysResponse]: + # 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._ListCryptoKeys(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crypto_key_versions( + self, + ) -> Callable[ + [service.ListCryptoKeyVersionsRequest], service.ListCryptoKeyVersionsResponse + ]: + # 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._ListCryptoKeyVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_import_jobs( + self, + ) -> Callable[[service.ListImportJobsRequest], service.ListImportJobsResponse]: + # 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._ListImportJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_key_rings( + self, + ) -> Callable[[service.ListKeyRingsRequest], service.ListKeyRingsResponse]: + # 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._ListKeyRings(self._session, self._host, self._interceptor) # type: ignore + + @property + def mac_sign(self) -> Callable[[service.MacSignRequest], service.MacSignResponse]: + # 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._MacSign(self._session, self._host, self._interceptor) # type: ignore + + @property + def mac_verify( + self, + ) -> Callable[[service.MacVerifyRequest], service.MacVerifyResponse]: + # 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._MacVerify(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_crypto_key_version( + self, + ) -> Callable[[service.RestoreCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._RestoreCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key( + self, + ) -> Callable[[service.UpdateCryptoKeyRequest], resources.CryptoKey]: + # 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._UpdateCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key_primary_version( + self, + ) -> Callable[[service.UpdateCryptoKeyPrimaryVersionRequest], resources.CryptoKey]: + # 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._UpdateCryptoKeyPrimaryVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key_version( + self, + ) -> Callable[[service.UpdateCryptoKeyVersionRequest], resources.CryptoKeyVersion]: + # 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._UpdateCryptoKeyVersion(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(KeyManagementServiceRestStub): + 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(KeyManagementServiceRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(KeyManagementServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(KeyManagementServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(KeyManagementServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("KeyManagementServiceRestTransport",) diff --git a/packages/google-cloud-kms/owlbot.py b/packages/google-cloud-kms/owlbot.py index 3964d3f50cd9..01ed89772c4c 100644 --- a/packages/google-cloud-kms/owlbot.py +++ b/packages/google-cloud-kms/owlbot.py @@ -45,7 +45,7 @@ ) # Rename `format_` to `format` to avoid breaking change - s.replace(library / "google/**/types/*.py", + s.replace(library / "**/*.py", "format_", "format" ) diff --git a/packages/google-cloud-kms/tests/system/test_system.py b/packages/google-cloud-kms/tests/system/test_system.py index 273e075cd7ff..5f2735a84fce 100644 --- a/packages/google-cloud-kms/tests/system/test_system.py +++ b/packages/google-cloud-kms/tests/system/test_system.py @@ -16,14 +16,17 @@ import os +import pytest + from google.cloud import kms_v1 class TestKeyManagementServiceClient(object): - def test_list_global_key_rings(self): + @pytest.mark.parametrize("transport", ["grpc", "rest"]) + def test_list_global_key_rings(self, transport): project_id = os.environ["PROJECT_ID"] # List key rings from the global location. - client = kms_v1.KeyManagementServiceClient() + client = kms_v1.KeyManagementServiceClient(transport=transport) parent = f"projects/{project_id}/locations/global" client.list_key_rings(request={"parent": parent}) diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_ekm_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_ekm_service.py index 869bf0e33944..8b33a634694a 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_ekm_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_ekm_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -30,17 +32,21 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account 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.kms_v1.services.ekm_service import ( EkmServiceAsyncClient, @@ -97,6 +103,7 @@ def test__get_default_mtls_endpoint(): [ (EkmServiceClient, "grpc"), (EkmServiceAsyncClient, "grpc_asyncio"), + (EkmServiceClient, "rest"), ], ) def test_ekm_service_client_from_service_account_info(client_class, transport_name): @@ -110,7 +117,11 @@ def test_ekm_service_client_from_service_account_info(client_class, transport_na assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudkms.googleapis.com:443") + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +129,7 @@ def test_ekm_service_client_from_service_account_info(client_class, transport_na [ (transports.EkmServiceGrpcTransport, "grpc"), (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EkmServiceRestTransport, "rest"), ], ) def test_ekm_service_client_service_account_always_use_jwt( @@ -143,6 +155,7 @@ def test_ekm_service_client_service_account_always_use_jwt( [ (EkmServiceClient, "grpc"), (EkmServiceAsyncClient, "grpc_asyncio"), + (EkmServiceClient, "rest"), ], ) def test_ekm_service_client_from_service_account_file(client_class, transport_name): @@ -163,13 +176,18 @@ def test_ekm_service_client_from_service_account_file(client_class, transport_na assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudkms.googleapis.com:443") + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) def test_ekm_service_client_get_transport_class(): transport = EkmServiceClient.get_transport_class() available_transports = [ transports.EkmServiceGrpcTransport, + transports.EkmServiceRestTransport, ] assert transport in available_transports @@ -186,6 +204,7 @@ def test_ekm_service_client_get_transport_class(): transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -329,6 +348,8 @@ def test_ekm_service_client_client_options( "grpc_asyncio", "false", ), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "true"), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -522,6 +543,7 @@ def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), ], ) def test_ekm_service_client_client_options_scopes( @@ -557,6 +579,7 @@ def test_ekm_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", None), ], ) def test_ekm_service_client_client_options_credentials_file( @@ -1891,142 +1914,1463 @@ async def test_update_ekm_connection_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EkmServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + ekm_service.ListEkmConnectionsRequest, + dict, + ], +) +def test_list_ekm_connections_rest(request_type): + client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = EkmServiceClient( - 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 = ekm_service.ListEkmConnectionsResponse( + next_page_token="next_page_token_value", + total_size=1086, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EkmServiceGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ekm_service.ListEkmConnectionsResponse.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_ekm_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_ekm_connections_rest_required_fields( + request_type=ekm_service.ListEkmConnectionsRequest, +): + transport_class = transports.EkmServiceRestTransport + + 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_ekm_connections._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_ekm_connections._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 = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.ListEkmConnectionsResponse() + # 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 = ekm_service.ListEkmConnectionsResponse.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_ekm_connections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_ekm_connections_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_ekm_connections._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.EkmServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_ekm_connections_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EkmServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options=options, - transport=transport, + client = EkmServiceClient(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.EkmServiceRestInterceptor, "post_list_ekm_connections" + ) as post, mock.patch.object( + transports.EkmServiceRestInterceptor, "pre_list_ekm_connections" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.ListEkmConnectionsRequest.pb( + ekm_service.ListEkmConnectionsRequest() + ) + 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 = ekm_service.ListEkmConnectionsResponse.to_json( + ekm_service.ListEkmConnectionsResponse() ) - # 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 = EkmServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = ekm_service.ListEkmConnectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.ListEkmConnectionsResponse() + + client.list_ekm_connections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.EkmServiceGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_ekm_connections_rest_bad_request( + transport: str = "rest", request_type=ekm_service.ListEkmConnectionsRequest +): + client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = EkmServiceClient( - 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.EkmServiceGrpcTransport( + # 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_ekm_connections(request) + + +def test_list_ekm_connections_rest_flattened(): + client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = EkmServiceClient(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 = ekm_service.ListEkmConnectionsResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EkmServiceGrpcTransport( + # 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 = ekm_service.ListEkmConnectionsResponse.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_ekm_connections(**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/*}/ekmConnections" + % client.transport._host, + args[1], + ) + + +def test_list_ekm_connections_rest_flattened_error(transport: str = "rest"): + client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.EkmServiceGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent="parent_value", + ) + + +def test_list_ekm_connections_rest_pager(transport: str = "rest"): + client = EkmServiceClient( 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 = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token="abc", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token="def", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token="ghi", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + ekm_service.ListEkmConnectionsResponse.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.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - ], -) -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_ekm_connections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) for i in results) + + pages = list(client.list_ekm_connections(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", + ekm_service.GetEkmConnectionRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = EkmServiceClient.get_transport_class(transport_name)( +def test_get_ekm_connection_rest(request_type): + client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/ekmConnections/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 = ekm_service.EkmConnection( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ekm_service.EkmConnection.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_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_get_ekm_connection_rest_required_fields( + request_type=ekm_service.GetEkmConnectionRequest, +): + transport_class = transports.EkmServiceRestTransport + + 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_ekm_connection._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_ekm_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.EkmServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # 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 = ekm_service.EkmConnection.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_ekm_connection(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_ekm_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EkmServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(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.EkmServiceRestInterceptor, "post_get_ekm_connection" + ) as post, mock.patch.object( + transports.EkmServiceRestInterceptor, "pre_get_ekm_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.GetEkmConnectionRequest.pb( + ekm_service.GetEkmConnectionRequest() + ) + 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 = ekm_service.EkmConnection.to_json( + ekm_service.EkmConnection() ) + request = ekm_service.GetEkmConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() -def test_ekm_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EkmServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.get_ekm_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ekm_connection_rest_bad_request( + transport: str = "rest", request_type=ekm_service.GetEkmConnectionRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/ekmConnections/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_ekm_connection(request) + + +def test_get_ekm_connection_rest_flattened(): + client = EkmServiceClient( + 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 = ekm_service.EkmConnection() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/ekmConnections/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 = ekm_service.EkmConnection.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_ekm_connection(**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/*/ekmConnections/*}" + % client.transport._host, + args[1], + ) + + +def test_get_ekm_connection_rest_flattened_error(transport: str = "rest"): + client = EkmServiceClient( + 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_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name="name_value", + ) + + +def test_get_ekm_connection_rest_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + ekm_service.CreateEkmConnectionRequest, + dict, + ], +) +def test_create_ekm_connection_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["ekm_connection"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "service_resolvers": [ + { + "service_directory_service": "service_directory_service_value", + "endpoint_filter": "endpoint_filter_value", + "hostname": "hostname_value", + "server_certificates": [ + { + "raw_der": b"raw_der_blob", + "parsed": True, + "issuer": "issuer_value", + "subject": "subject_value", + "subject_alternative_dns_names": [ + "subject_alternative_dns_names_value1", + "subject_alternative_dns_names_value2", + ], + "not_before_time": {}, + "not_after_time": {}, + "serial_number": "serial_number_value", + "sha256_fingerprint": "sha256_fingerprint_value", + } + ], + } + ], + "etag": "etag_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 = ekm_service.EkmConnection( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ekm_service.EkmConnection.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.create_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_create_ekm_connection_rest_required_fields( + request_type=ekm_service.CreateEkmConnectionRequest, +): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["ekm_connection_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 "ekmConnectionId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ekm_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "ekmConnectionId" in jsonified_request + assert jsonified_request["ekmConnectionId"] == request_init["ekm_connection_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["ekmConnectionId"] = "ekm_connection_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ekm_connection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ekm_connection_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 "ekmConnectionId" in jsonified_request + assert jsonified_request["ekmConnectionId"] == "ekm_connection_id_value" + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = ekm_service.EkmConnection.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.create_ekm_connection(request) + + expected_params = [ + ( + "ekmConnectionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("ekmConnectionId",)) + & set( + ( + "parent", + "ekmConnectionId", + "ekmConnection", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(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.EkmServiceRestInterceptor, "post_create_ekm_connection" + ) as post, mock.patch.object( + transports.EkmServiceRestInterceptor, "pre_create_ekm_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.CreateEkmConnectionRequest.pb( + ekm_service.CreateEkmConnectionRequest() + ) + 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 = ekm_service.EkmConnection.to_json( + ekm_service.EkmConnection() + ) + + request = ekm_service.CreateEkmConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() + + client.create_ekm_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_ekm_connection_rest_bad_request( + transport: str = "rest", request_type=ekm_service.CreateEkmConnectionRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["ekm_connection"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "service_resolvers": [ + { + "service_directory_service": "service_directory_service_value", + "endpoint_filter": "endpoint_filter_value", + "hostname": "hostname_value", + "server_certificates": [ + { + "raw_der": b"raw_der_blob", + "parsed": True, + "issuer": "issuer_value", + "subject": "subject_value", + "subject_alternative_dns_names": [ + "subject_alternative_dns_names_value1", + "subject_alternative_dns_names_value2", + ], + "not_before_time": {}, + "not_after_time": {}, + "serial_number": "serial_number_value", + "sha256_fingerprint": "sha256_fingerprint_value", + } + ], + } + ], + "etag": "etag_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_ekm_connection(request) + + +def test_create_ekm_connection_rest_flattened(): + client = EkmServiceClient( + 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 = ekm_service.EkmConnection() + + # 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", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(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 = ekm_service.EkmConnection.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.create_ekm_connection(**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/*}/ekmConnections" + % client.transport._host, + args[1], + ) + + +def test_create_ekm_connection_rest_flattened_error(transport: str = "rest"): + client = EkmServiceClient( + 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_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), + ) + + +def test_create_ekm_connection_rest_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + ekm_service.UpdateEkmConnectionRequest, + dict, + ], +) +def test_update_ekm_connection_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "ekm_connection": { + "name": "projects/sample1/locations/sample2/ekmConnections/sample3" + } + } + request_init["ekm_connection"] = { + "name": "projects/sample1/locations/sample2/ekmConnections/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "service_resolvers": [ + { + "service_directory_service": "service_directory_service_value", + "endpoint_filter": "endpoint_filter_value", + "hostname": "hostname_value", + "server_certificates": [ + { + "raw_der": b"raw_der_blob", + "parsed": True, + "issuer": "issuer_value", + "subject": "subject_value", + "subject_alternative_dns_names": [ + "subject_alternative_dns_names_value1", + "subject_alternative_dns_names_value2", + ], + "not_before_time": {}, + "not_after_time": {}, + "serial_number": "serial_number_value", + "sha256_fingerprint": "sha256_fingerprint_value", + } + ], + } + ], + "etag": "etag_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 = ekm_service.EkmConnection( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ekm_service.EkmConnection.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.update_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_update_ekm_connection_rest_required_fields( + request_type=ekm_service.UpdateEkmConnectionRequest, +): + transport_class = transports.EkmServiceRestTransport + + 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_ekm_connection._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_ekm_connection._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 = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # 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 + + pb_return_value = ekm_service.EkmConnection.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.update_ekm_connection(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "ekmConnection", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(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.EkmServiceRestInterceptor, "post_update_ekm_connection" + ) as post, mock.patch.object( + transports.EkmServiceRestInterceptor, "pre_update_ekm_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.UpdateEkmConnectionRequest.pb( + ekm_service.UpdateEkmConnectionRequest() + ) + 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 = ekm_service.EkmConnection.to_json( + ekm_service.EkmConnection() + ) + + request = ekm_service.UpdateEkmConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() + + client.update_ekm_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_ekm_connection_rest_bad_request( + transport: str = "rest", request_type=ekm_service.UpdateEkmConnectionRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "ekm_connection": { + "name": "projects/sample1/locations/sample2/ekmConnections/sample3" + } + } + request_init["ekm_connection"] = { + "name": "projects/sample1/locations/sample2/ekmConnections/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "service_resolvers": [ + { + "service_directory_service": "service_directory_service_value", + "endpoint_filter": "endpoint_filter_value", + "hostname": "hostname_value", + "server_certificates": [ + { + "raw_der": b"raw_der_blob", + "parsed": True, + "issuer": "issuer_value", + "subject": "subject_value", + "subject_alternative_dns_names": [ + "subject_alternative_dns_names_value1", + "subject_alternative_dns_names_value2", + ], + "not_before_time": {}, + "not_after_time": {}, + "serial_number": "serial_number_value", + "sha256_fingerprint": "sha256_fingerprint_value", + } + ], + } + ], + "etag": "etag_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_ekm_connection(request) + + +def test_update_ekm_connection_rest_flattened(): + client = EkmServiceClient( + 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 = ekm_service.EkmConnection() + + # get arguments that satisfy an http rule for this method + sample_request = { + "ekm_connection": { + "name": "projects/sample1/locations/sample2/ekmConnections/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + ekm_connection=ekm_service.EkmConnection(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 + pb_return_value = ekm_service.EkmConnection.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.update_ekm_connection(**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/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}" + % client.transport._host, + args[1], + ) + + +def test_update_ekm_connection_rest_flattened_error(transport: str = "rest"): + client = EkmServiceClient( + 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_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_ekm_connection_rest_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient( + 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 = EkmServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EkmServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EkmServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + transports.EkmServiceRestTransport, + ], +) +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 = EkmServiceClient.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 = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EkmServiceGrpcTransport, + ) + + +def test_ekm_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_ekm_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. methods = ( "list_ekm_connections", "get_ekm_connection", @@ -2035,545 +3379,1174 @@ def test_ekm_service_base_transport(): "set_iam_policy", "get_iam_policy", "test_iam_permissions", + "get_location", + "list_locations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_ekm_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +def test_ekm_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport() + adc.assert_called_once() + + +def test_ekm_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EkmServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + ], +) +def test_ekm_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + transports.EkmServiceRestTransport, + ], +) +def test_ekm_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EkmServiceGrpcTransport, grpc_helpers), + (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_ekm_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.EkmServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_ekm_service_host_no_port(transport_name): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_ekm_service_host_with_port(transport_name): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_ekm_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EkmServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EkmServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_ekm_connections._session + session2 = client2.transport.list_ekm_connections._session + assert session1 != session2 + session1 = client1.transport.get_ekm_connection._session + session2 = client2.transport.get_ekm_connection._session + assert session1 != session2 + session1 = client1.transport.create_ekm_connection._session + session2 = client2.transport.create_ekm_connection._session + assert session1 != session2 + session1 = client1.transport.update_ekm_connection._session + session2 = client2.transport.update_ekm_connection._session + assert session1 != session2 + + +def test_ekm_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_ekm_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_ekm_connection_path(): + project = "squid" + location = "clam" + ekm_connection = "whelk" + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, + location=location, + ekm_connection=ekm_connection, + ) + actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) + assert expected == actual + + +def test_parse_ekm_connection_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ekm_connection": "nudibranch", + } + path = EkmServiceClient.ekm_connection_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_ekm_connection_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + actual = EkmServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", + } + path = EkmServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = EkmServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = EkmServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = EkmServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = EkmServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + actual = EkmServiceClient.common_organization_path(organization) + assert expected == actual - with pytest.raises(NotImplementedError): - transport.close() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = EkmServiceClient.common_organization_path(**expected) + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = EkmServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = EkmServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EkmServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = EkmServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() -def test_ekm_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EkmServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - quota_project_id="octopus", + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = EkmServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) + prep.assert_called_once_with(client_info) -def test_ekm_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EkmServiceTransport() - adc.assert_called_once() +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() -def test_ekm_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EkmServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - quota_project_id=None, - ) +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - ], -) -def test_ekm_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - quota_project_id="octopus", - ) + # 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( - "transport_class", + "request_type", [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, + locations_pb2.GetLocationRequest, + dict, ], ) -def test_ekm_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_get_location_rest(request_type): + client = EkmServiceClient( + 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 = EkmServiceClient( + 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( - "transport_class,grpc_helpers", + "request_type", [ - (transports.EkmServiceGrpcTransport, grpc_helpers), - (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async), + locations_pb2.ListLocationsRequest, + dict, ], ) -def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +def test_list_locations_rest(request_type): + client = EkmServiceClient( + 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() - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # 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) -@pytest.mark.parametrize( - "transport_class", - [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], -) -def test_ekm_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request + ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + iam_policy_pb2.GetIamPolicyRequest, + dict, ], ) -def test_ekm_service_host_no_port(transport_name): +def test_get_iam_policy_rest(request_type): client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudkms.googleapis.com" - ), - transport=transport_name, + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request ) - assert client.transport._host == ("cloudkms.googleapis.com:443") + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + iam_policy_pb2.SetIamPolicyRequest, + dict, ], ) -def test_ekm_service_host_with_port(transport_name): +def test_set_iam_policy_rest(request_type): client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudkms.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("cloudkms.googleapis.com:8000") + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_ekm_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that channel is used if provided. - transport = transports.EkmServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + response = client.set_iam_policy(request) + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) -def test_ekm_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.EkmServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/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.test_iam_permissions(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", - [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], ) -def test_ekm_service_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_test_iam_permissions_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/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 = iam_policy_pb2.TestIamPermissionsResponse() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + response = client.test_iam_permissions(request) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], -) -def test_ekm_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) +def test_list_locations(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_ekm_connection_path(): - project = "squid" - location = "clam" - ekm_connection = "whelk" - expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( - project=project, - location=location, - ekm_connection=ekm_connection, + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_ekm_connection_path(): - expected = { - "project": "octopus", - "location": "oyster", - "ekm_connection": "nudibranch", - } - path = EkmServiceClient.ekm_connection_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_ekm_connection_path(path) - assert expected == actual + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_service_path(): - project = "cuttlefish" - location = "mussel" - namespace = "winkle" - service = "nautilus" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( - project=project, - location=location, - namespace=namespace, - service=service, + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = EkmServiceClient.service_path(project, location, namespace, service) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_service_path(): - expected = { - "project": "scallop", - "location": "abalone", - "namespace": "squid", - "service": "clam", - } - path = EkmServiceClient.service_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_service_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +def test_list_locations_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = EkmServiceClient.common_billing_account_path(billing_account) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = EkmServiceClient.common_billing_account_path(**expected) - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_billing_account_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +def test_get_location(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = EkmServiceClient.common_folder_path(folder) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = EkmServiceClient.common_folder_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_folder_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = EkmServiceClient.common_organization_path(organization) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = EkmServiceClient.common_organization_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_organization_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, - ) - actual = EkmServiceClient.common_project_path(project) - assert expected == actual +def test_get_location_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials()) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = EkmServiceClient.common_project_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_project_path(path) - assert expected == actual + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = EkmServiceClient.common_location_path(project, location) - assert expected == actual +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials()) -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = EkmServiceClient.common_location_path(**expected) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_location_path(path) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.EkmServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_get_location_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() - with mock.patch.object( - transports.EkmServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = EkmServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + response = client.get_location( + request={ + "name": "locations/abc", + } ) - prep.assert_called_once_with(client_info) + call.assert_called() @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_get_location_from_dict_async(): client = EkmServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() def test_set_iam_policy(transport: str = "grpc"): @@ -3086,6 +5059,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3103,6 +5077,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index a5edf94def22..e08d03309815 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -30,12 +32,14 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import duration_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 from google.protobuf import wrappers_pb2 # type: ignore import grpc @@ -43,6 +47,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.kms_v1.services.key_management_service import ( KeyManagementServiceAsyncClient, @@ -103,6 +109,7 @@ def test__get_default_mtls_endpoint(): [ (KeyManagementServiceClient, "grpc"), (KeyManagementServiceAsyncClient, "grpc_asyncio"), + (KeyManagementServiceClient, "rest"), ], ) def test_key_management_service_client_from_service_account_info( @@ -118,7 +125,11 @@ def test_key_management_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudkms.googleapis.com:443") + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) @pytest.mark.parametrize( @@ -126,6 +137,7 @@ def test_key_management_service_client_from_service_account_info( [ (transports.KeyManagementServiceGrpcTransport, "grpc"), (transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.KeyManagementServiceRestTransport, "rest"), ], ) def test_key_management_service_client_service_account_always_use_jwt( @@ -151,6 +163,7 @@ def test_key_management_service_client_service_account_always_use_jwt( [ (KeyManagementServiceClient, "grpc"), (KeyManagementServiceAsyncClient, "grpc_asyncio"), + (KeyManagementServiceClient, "rest"), ], ) def test_key_management_service_client_from_service_account_file( @@ -173,13 +186,18 @@ def test_key_management_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudkms.googleapis.com:443") + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) def test_key_management_service_client_get_transport_class(): transport = KeyManagementServiceClient.get_transport_class() available_transports = [ transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceRestTransport, ] assert transport in available_transports @@ -200,6 +218,11 @@ def test_key_management_service_client_get_transport_class(): transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + KeyManagementServiceClient, + transports.KeyManagementServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -355,6 +378,18 @@ def test_key_management_service_client_client_options( "grpc_asyncio", "false", ), + ( + KeyManagementServiceClient, + transports.KeyManagementServiceRestTransport, + "rest", + "true", + ), + ( + KeyManagementServiceClient, + transports.KeyManagementServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -558,6 +593,11 @@ def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_ transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + KeyManagementServiceClient, + transports.KeyManagementServiceRestTransport, + "rest", + ), ], ) def test_key_management_service_client_client_options_scopes( @@ -598,6 +638,12 @@ def test_key_management_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + KeyManagementServiceClient, + transports.KeyManagementServiceRestTransport, + "rest", + None, + ), ], ) def test_key_management_service_client_client_options_credentials_file( @@ -8174,825 +8220,9550 @@ async def test_generate_random_bytes_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.ListKeyRingsRequest, + dict, + ], +) +def test_list_key_rings_rest(request_type): + client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - 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 = service.ListKeyRingsResponse( + next_page_token="next_page_token_value", + total_size=1086, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListKeyRingsResponse.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_key_rings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRequest): + transport_class = transports.KeyManagementServiceRestTransport + + 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_key_rings._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_key_rings._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 = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListKeyRingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListKeyRingsResponse.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_key_rings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_key_rings_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + unset_fields = transport.list_key_rings._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.KeyManagementServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_key_rings_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options=options, - transport=transport, + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_list_key_rings" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_list_key_rings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListKeyRingsRequest.pb(service.ListKeyRingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListKeyRingsResponse.to_json( + service.ListKeyRingsResponse() ) - # 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 = KeyManagementServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = service.ListKeyRingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListKeyRingsResponse() + + client.list_key_rings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_key_rings_rest_bad_request( + transport: str = "rest", request_type=service.ListKeyRingsRequest +): + client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - 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.KeyManagementServiceGrpcTransport( + # 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_key_rings(request) + + +def test_list_key_rings_rest_flattened(): + client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = KeyManagementServiceClient(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 = service.ListKeyRingsResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.KeyManagementServiceGrpcTransport( + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListKeyRingsResponse.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_key_rings(**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/*}/keyRings" % client.transport._host, + args[1], + ) + + +def test_list_key_rings_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_key_rings( + service.ListKeyRingsRequest(), + parent="parent_value", + ) + + +def test_list_key_rings_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( 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 = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token="abc", + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token="def", + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token="ghi", + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListKeyRingsResponse.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.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -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_key_rings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyRing) for i in results) + + pages = list(client.list_key_rings(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", + service.ListCryptoKeysRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = KeyManagementServiceClient.get_transport_class(transport_name)( +def test_list_crypto_keys_rest(request_type): + client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.KeyManagementServiceGrpcTransport, - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCryptoKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_key_management_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_crypto_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_crypto_keys_rest_required_fields( + request_type=service.ListCryptoKeysRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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 -def test_key_management_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_crypto_keys._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_crypto_keys._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", + "version_view", ) + ) + jsonified_request.update(unset_fields) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_key_rings", - "list_crypto_keys", - "list_crypto_key_versions", - "list_import_jobs", - "get_key_ring", - "get_crypto_key", - "get_crypto_key_version", - "get_public_key", - "get_import_job", - "create_key_ring", - "create_crypto_key", - "create_crypto_key_version", - "import_crypto_key_version", - "create_import_job", - "update_crypto_key", - "update_crypto_key_version", - "update_crypto_key_primary_version", - "destroy_crypto_key_version", - "restore_crypto_key_version", - "encrypt", - "decrypt", - "asymmetric_sign", - "asymmetric_decrypt", - "mac_sign", - "mac_verify", - "generate_random_bytes", - "set_iam_policy", - "get_iam_policy", - "test_iam_permissions", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" - with pytest.raises(NotImplementedError): - transport.close() + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse() + # 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 - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCryptoKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_key_management_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_crypto_keys(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_crypto_keys_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_crypto_keys._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "versionView", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crypto_keys_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "post_list_crypto_keys" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_keys" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCryptoKeysRequest.pb(service.ListCryptoKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCryptoKeysResponse.to_json( + service.ListCryptoKeysResponse() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - quota_project_id="octopus", + + request = service.ListCryptoKeysRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCryptoKeysResponse() + + client.list_crypto_keys( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_key_management_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport() - adc.assert_called_once() +def test_list_crypto_keys_rest_bad_request( + transport: str = "rest", request_type=service.ListCryptoKeysRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_key_management_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KeyManagementServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/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_crypto_keys(request) + + +def test_list_crypto_keys_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/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 = service.ListCryptoKeysResponse.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_crypto_keys(**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/*/keyRings/*}/cryptoKeys" + % client.transport._host, + args[1], + ) + + +def test_list_crypto_keys_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_keys( + service.ListCryptoKeysRequest(), + parent="parent_value", + ) + + +def test_list_crypto_keys_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token="abc", ), - quota_project_id=None, + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token="def", + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token="ghi", + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCryptoKeysResponse.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/keyRings/sample3" + } + + pager = client.list_crypto_keys(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKey) for i in results) + + pages = list(client.list_crypto_keys(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCryptoKeyVersionsRequest, + dict, + ], +) +def test_list_crypto_key_versions_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = service.ListCryptoKeyVersionsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCryptoKeyVersionsResponse.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_crypto_key_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_crypto_key_versions_rest_required_fields( + request_type=service.ListCryptoKeyVersionsRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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_crypto_key_versions._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_crypto_key_versions._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", + "view", + ) + ) + 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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeyVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCryptoKeyVersionsResponse.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_crypto_key_versions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_crypto_key_versions_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_crypto_key_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crypto_key_versions_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_list_crypto_key_versions" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_key_versions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCryptoKeyVersionsRequest.pb( + service.ListCryptoKeyVersionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCryptoKeyVersionsResponse.to_json( + service.ListCryptoKeyVersionsResponse() + ) + + request = service.ListCryptoKeyVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCryptoKeyVersionsResponse() + + client.list_crypto_key_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crypto_key_versions_rest_bad_request( + transport: str = "rest", request_type=service.ListCryptoKeyVersionsRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.list_crypto_key_versions(request) + + +def test_list_crypto_key_versions_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeyVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCryptoKeyVersionsResponse.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_crypto_key_versions(**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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + % client.transport._host, + args[1], + ) + + +def test_list_crypto_key_versions_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent="parent_value", + ) + + +def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token="abc", + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token="def", + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token="ghi", + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCryptoKeyVersionsResponse.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/keyRings/sample3/cryptoKeys/sample4" + } + + pager = client.list_crypto_key_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKeyVersion) for i in results) + + pages = list(client.list_crypto_key_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListImportJobsRequest, + dict, + ], +) +def test_list_import_jobs_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListImportJobsResponse.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_import_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_import_jobs_rest_required_fields( + request_type=service.ListImportJobsRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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_import_jobs._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_import_jobs._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListImportJobsResponse.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_import_jobs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_import_jobs_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_import_jobs._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_import_jobs_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_list_import_jobs" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_list_import_jobs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListImportJobsRequest.pb(service.ListImportJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListImportJobsResponse.to_json( + service.ListImportJobsResponse() + ) + + request = service.ListImportJobsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListImportJobsResponse() + + client.list_import_jobs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_import_jobs_rest_bad_request( + transport: str = "rest", request_type=service.ListImportJobsRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/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_import_jobs(request) + + +def test_list_import_jobs_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/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 = service.ListImportJobsResponse.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_import_jobs(**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/*/keyRings/*}/importJobs" + % client.transport._host, + args[1], + ) + + +def test_list_import_jobs_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_import_jobs( + service.ListImportJobsRequest(), + parent="parent_value", + ) + + +def test_list_import_jobs_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token="abc", + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token="def", + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token="ghi", + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListImportJobsResponse.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/keyRings/sample3" + } + + pager = client.list_import_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ImportJob) for i in results) + + pages = list(client.list_import_jobs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetKeyRingRequest, + dict, + ], +) +def test_get_key_ring_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/keyRings/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 = resources.KeyRing( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.KeyRing.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_key_ring(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == "name_value" + + +def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingRequest): + transport_class = transports.KeyManagementServiceRestTransport + + 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_key_ring._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_key_ring._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + # 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 = resources.KeyRing.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_key_ring(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_key_ring_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_key_ring_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_get_key_ring" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_get_key_ring" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetKeyRingRequest.pb(service.GetKeyRingRequest()) + 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 = resources.KeyRing.to_json(resources.KeyRing()) + + request = service.GetKeyRingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyRing() + + client.get_key_ring( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_key_ring_rest_bad_request( + transport: str = "rest", request_type=service.GetKeyRingRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/keyRings/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_key_ring(request) + + +def test_get_key_ring_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.KeyRing() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/keyRings/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 = resources.KeyRing.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_key_ring(**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/*/keyRings/*}" % client.transport._host, + args[1], + ) + + +def test_get_key_ring_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_key_ring( + service.GetKeyRingRequest(), + name="name_value", + ) + + +def test_get_key_ring_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCryptoKeyRequest, + dict, + ], +) +def test_get_crypto_key_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = resources.CryptoKey( + name="name_value", + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", + rotation_period=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKey.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_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == "name_value" + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" + + +def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + 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_crypto_key._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_crypto_key._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # 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 = resources.CryptoKey.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_crypto_key(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_get_crypto_key" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCryptoKeyRequest.pb(service.GetCryptoKeyRequest()) + 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 = resources.CryptoKey.to_json(resources.CryptoKey()) + + request = service.GetCryptoKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.get_crypto_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_crypto_key_rest_bad_request( + transport: str = "rest", request_type=service.GetCryptoKeyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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_crypto_key(request) + + +def test_get_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = resources.CryptoKey.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_crypto_key(**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/*/keyRings/*/cryptoKeys/*}" + % client.transport._host, + args[1], + ) + + +def test_get_crypto_key_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key( + service.GetCryptoKeyRequest(), + name="name_value", + ) + + +def test_get_crypto_key_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCryptoKeyVersionRequest, + dict, + ], +) +def test_get_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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 = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_get_crypto_key_version_rest_required_fields( + request_type=service.GetCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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_crypto_key_version._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_crypto_key_version._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # 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 = resources.CryptoKeyVersion.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_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_get_crypto_key_version" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCryptoKeyVersionRequest.pb( + service.GetCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.GetCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.get_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.GetCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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_crypto_key_version(request) + + +def test_get_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # 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 = resources.CryptoKeyVersion.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_crypto_key_version(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_crypto_key_version_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name="name_value", + ) + + +def test_get_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetPublicKeyRequest, + dict, + ], +) +def test_get_public_key_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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 = resources.PublicKey( + pem="pem_value", + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name="name_value", + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.PublicKey.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_public_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == "pem_value" + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.name == "name_value" + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + 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_public_key._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_public_key._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.PublicKey() + # 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 = resources.PublicKey.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_public_key(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_public_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_public_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_public_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_get_public_key" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_get_public_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetPublicKeyRequest.pb(service.GetPublicKeyRequest()) + 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 = resources.PublicKey.to_json(resources.PublicKey()) + + request = service.GetPublicKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.PublicKey() + + client.get_public_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_public_key_rest_bad_request( + transport: str = "rest", request_type=service.GetPublicKeyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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_public_key(request) + + +def test_get_public_key_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.PublicKey() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # 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 = resources.PublicKey.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_public_key(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey" + % client.transport._host, + args[1], + ) + + +def test_get_public_key_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_public_key( + service.GetPublicKeyRequest(), + name="name_value", + ) + + +def test_get_public_key_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetImportJobRequest, + dict, + ], +) +def test_get_import_job_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/importJobs/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 = resources.ImportJob( + name="name_value", + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ImportJob.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_import_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == "name_value" + assert ( + response.import_method + == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRequest): + transport_class = transports.KeyManagementServiceRestTransport + + 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_import_job._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_import_job._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + # 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 = resources.ImportJob.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_import_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_import_job_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_import_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_import_job_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_get_import_job" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_get_import_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetImportJobRequest.pb(service.GetImportJobRequest()) + 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 = resources.ImportJob.to_json(resources.ImportJob()) + + request = service.GetImportJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ImportJob() + + client.get_import_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_import_job_rest_bad_request( + transport: str = "rest", request_type=service.GetImportJobRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/importJobs/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_import_job(request) + + +def test_get_import_job_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.ImportJob() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/importJobs/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 = resources.ImportJob.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_import_job(**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/*/keyRings/*/importJobs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_import_job_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_import_job( + service.GetImportJobRequest(), + name="name_value", + ) + + +def test_get_import_job_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateKeyRingRequest, + dict, + ], +) +def test_create_key_ring_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["key_ring"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.KeyRing( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.KeyRing.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.create_key_ring(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == "name_value" + + +def test_create_key_ring_rest_required_fields( + request_type=service.CreateKeyRingRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["key_ring_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 "keyRingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_key_ring._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == request_init["key_ring_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["keyRingId"] = "key_ring_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_key_ring._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("key_ring_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 "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == "key_ring_id_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.KeyRing.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.create_key_ring(request) + + expected_params = [ + ( + "keyRingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_key_ring_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("keyRingId",)) + & set( + ( + "parent", + "keyRingId", + "keyRing", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_key_ring_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_create_key_ring" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_create_key_ring" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateKeyRingRequest.pb(service.CreateKeyRingRequest()) + 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 = resources.KeyRing.to_json(resources.KeyRing()) + + request = service.CreateKeyRingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyRing() + + client.create_key_ring( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_key_ring_rest_bad_request( + transport: str = "rest", request_type=service.CreateKeyRingRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["key_ring"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + 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_key_ring(request) + + +def test_create_key_ring_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.KeyRing() + + # 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", + key_ring_id="key_ring_id_value", + key_ring=resources.KeyRing(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 = resources.KeyRing.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.create_key_ring(**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/*}/keyRings" % client.transport._host, + args[1], + ) + + +def test_create_key_ring_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_key_ring( + service.CreateKeyRingRequest(), + parent="parent_value", + key_ring_id="key_ring_id_value", + key_ring=resources.KeyRing(name="name_value"), + ) + + +def test_create_key_ring_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCryptoKeyRequest, + dict, + ], +) +def test_create_crypto_key_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request_init["crypto_key"] = { + "name": "name_value", + "primary": { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + }, + "purpose": 1, + "create_time": {}, + "next_rotation_time": {}, + "rotation_period": {"seconds": 751, "nanos": 543}, + "version_template": {"protection_level": 1, "algorithm": 1}, + "labels": {}, + "import_only": True, + "destroy_scheduled_duration": {}, + "crypto_key_backend": "crypto_key_backend_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 = resources.CryptoKey( + name="name_value", + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", + rotation_period=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKey.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.create_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == "name_value" + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" + + +def test_create_crypto_key_rest_required_fields( + request_type=service.CreateCryptoKeyRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["crypto_key_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 "cryptoKeyId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_crypto_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == request_init["crypto_key_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["cryptoKeyId"] = "crypto_key_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_crypto_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "crypto_key_id", + "skip_initial_version_creation", + ) + ) + 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 "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == "crypto_key_id_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKey.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.create_crypto_key(request) + + expected_params = [ + ( + "cryptoKeyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "cryptoKeyId", + "skipInitialVersionCreation", + ) + ) + & set( + ( + "parent", + "cryptoKeyId", + "cryptoKey", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_create_crypto_key" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCryptoKeyRequest.pb(service.CreateCryptoKeyRequest()) + 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 = resources.CryptoKey.to_json(resources.CryptoKey()) + + request = service.CreateCryptoKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.create_crypto_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_crypto_key_rest_bad_request( + transport: str = "rest", request_type=service.CreateCryptoKeyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request_init["crypto_key"] = { + "name": "name_value", + "primary": { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + }, + "purpose": 1, + "create_time": {}, + "next_rotation_time": {}, + "rotation_period": {"seconds": 751, "nanos": 543}, + "version_template": {"protection_level": 1, "algorithm": 1}, + "labels": {}, + "import_only": True, + "destroy_scheduled_duration": {}, + "crypto_key_backend": "crypto_key_backend_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_crypto_key(request) + + +def test_create_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + crypto_key_id="crypto_key_id_value", + crypto_key=resources.CryptoKey(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 = resources.CryptoKey.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.create_crypto_key(**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/*/keyRings/*}/cryptoKeys" + % client.transport._host, + args[1], + ) + + +def test_create_crypto_key_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key( + service.CreateCryptoKeyRequest(), + parent="parent_value", + crypto_key_id="crypto_key_id_value", + crypto_key=resources.CryptoKey(name="name_value"), + ) + + +def test_create_crypto_key_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCryptoKeyVersionRequest, + dict, + ], +) +def test_create_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + request_init["crypto_key_version"] = { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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.create_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_create_crypto_key_version_rest_required_fields( + request_type=service.CreateCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_crypto_key_version._get_unset_required_fields(jsonified_request) + 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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKeyVersion.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.create_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "cryptoKeyVersion", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_create_crypto_key_version" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCryptoKeyVersionRequest.pb( + service.CreateCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.CreateCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.create_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.CreateCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + request_init["crypto_key_version"] = { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_crypto_key_version(request) + + +def test_create_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + crypto_key_version=resources.CryptoKeyVersion(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 = resources.CryptoKeyVersion.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.create_crypto_key_version(**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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + % client.transport._host, + args[1], + ) + + +def test_create_crypto_key_version_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent="parent_value", + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + ) + + +def test_create_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ImportCryptoKeyVersionRequest, + dict, + ], +) +def test_import_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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.import_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_import_crypto_key_version_rest_required_fields( + request_type=service.ImportCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["import_job"] = "" + 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() + ).import_crypto_key_version._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" + jsonified_request["importJob"] = "import_job_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_crypto_key_version._get_unset_required_fields(jsonified_request) + 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 "importJob" in jsonified_request + assert jsonified_request["importJob"] == "import_job_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKeyVersion.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.import_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "algorithm", + "importJob", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_import_crypto_key_version" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_import_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ImportCryptoKeyVersionRequest.pb( + service.ImportCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.ImportCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.import_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.ImportCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.import_crypto_key_version(request) + + +def test_import_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateImportJobRequest, + dict, + ], +) +def test_create_import_job_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request_init["import_job"] = { + "name": "name_value", + "import_method": 1, + "protection_level": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "expire_time": {}, + "expire_event_time": {}, + "state": 1, + "public_key": {"pem": "pem_value"}, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob( + name="name_value", + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ImportJob.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.create_import_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == "name_value" + assert ( + response.import_method + == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +def test_create_import_job_rest_required_fields( + request_type=service.CreateImportJobRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["import_job_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 "importJobId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_import_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "importJobId" in jsonified_request + assert jsonified_request["importJobId"] == request_init["import_job_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["importJobId"] = "import_job_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_import_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("import_job_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 "importJobId" in jsonified_request + assert jsonified_request["importJobId"] == "import_job_id_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.ImportJob.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.create_import_job(request) + + expected_params = [ + ( + "importJobId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_import_job_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_import_job._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("importJobId",)) + & set( + ( + "parent", + "importJobId", + "importJob", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_import_job_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_create_import_job" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_create_import_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateImportJobRequest.pb(service.CreateImportJobRequest()) + 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 = resources.ImportJob.to_json(resources.ImportJob()) + + request = service.CreateImportJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ImportJob() + + client.create_import_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_import_job_rest_bad_request( + transport: str = "rest", request_type=service.CreateImportJobRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/keyRings/sample3"} + request_init["import_job"] = { + "name": "name_value", + "import_method": 1, + "protection_level": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "expire_time": {}, + "expire_event_time": {}, + "state": 1, + "public_key": {"pem": "pem_value"}, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_import_job(request) + + +def test_create_import_job_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.ImportJob() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(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 = resources.ImportJob.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.create_import_job(**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/*/keyRings/*}/importJobs" + % client.transport._host, + args[1], + ) + + +def test_create_import_job_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_import_job( + service.CreateImportJobRequest(), + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(name="name_value"), + ) + + +def test_create_import_job_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCryptoKeyRequest, + dict, + ], +) +def test_update_crypto_key_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "crypto_key": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + } + request_init["crypto_key"] = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4", + "primary": { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + }, + "purpose": 1, + "create_time": {}, + "next_rotation_time": {}, + "rotation_period": {"seconds": 751, "nanos": 543}, + "version_template": {"protection_level": 1, "algorithm": 1}, + "labels": {}, + "import_only": True, + "destroy_scheduled_duration": {}, + "crypto_key_backend": "crypto_key_backend_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 = resources.CryptoKey( + name="name_value", + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", + rotation_period=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKey.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.update_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == "name_value" + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" + + +def test_update_crypto_key_rest_required_fields( + request_type=service.UpdateCryptoKeyRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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_crypto_key._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_crypto_key._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # 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 + + pb_return_value = resources.CryptoKey.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.update_crypto_key(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "cryptoKey", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_update_crypto_key" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyRequest.pb(service.UpdateCryptoKeyRequest()) + 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 = resources.CryptoKey.to_json(resources.CryptoKey()) + + request = service.UpdateCryptoKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.update_crypto_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCryptoKeyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "crypto_key": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + } + request_init["crypto_key"] = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4", + "primary": { + "name": "name_value", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + }, + "purpose": 1, + "create_time": {}, + "next_rotation_time": {}, + "rotation_period": {"seconds": 751, "nanos": 543}, + "version_template": {"protection_level": 1, "algorithm": 1}, + "labels": {}, + "import_only": True, + "destroy_scheduled_duration": {}, + "crypto_key_backend": "crypto_key_backend_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_crypto_key(request) + + +def test_update_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = { + "crypto_key": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + crypto_key=resources.CryptoKey(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 + pb_return_value = resources.CryptoKey.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.update_crypto_key(**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/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" + % client.transport._host, + args[1], + ) + + +def test_update_crypto_key_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_crypto_key_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCryptoKeyVersionRequest, + dict, + ], +) +def test_update_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "crypto_key_version": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + } + request_init["crypto_key_version"] = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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.update_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_update_crypto_key_version_rest_required_fields( + request_type=service.UpdateCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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_crypto_key_version._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_crypto_key_version._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # 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 + + pb_return_value = resources.CryptoKeyVersion.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.update_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "cryptoKeyVersion", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_update_crypto_key_version" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyVersionRequest.pb( + service.UpdateCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.UpdateCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.update_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "crypto_key_version": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + } + request_init["crypto_key_version"] = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5", + "state": 5, + "protection_level": 1, + "algorithm": 1, + "attestation": { + "format": 3, + "content": b"content_blob", + "cert_chains": { + "cavium_certs": ["cavium_certs_value1", "cavium_certs_value2"], + "google_card_certs": [ + "google_card_certs_value1", + "google_card_certs_value2", + ], + "google_partition_certs": [ + "google_partition_certs_value1", + "google_partition_certs_value2", + ], + }, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "generate_time": {}, + "destroy_time": {}, + "destroy_event_time": {}, + "import_job": "import_job_value", + "import_time": {}, + "import_failure_reason": "import_failure_reason_value", + "external_protection_level_options": { + "external_key_uri": "external_key_uri_value", + "ekm_connection_key_path": "ekm_connection_key_path_value", + }, + "reimport_eligible": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_crypto_key_version(request) + + +def test_update_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "crypto_key_version": { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + crypto_key_version=resources.CryptoKeyVersion(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 + pb_return_value = resources.CryptoKeyVersion.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.update_crypto_key_version(**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/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_crypto_key_version_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCryptoKeyPrimaryVersionRequest, + dict, + ], +) +def test_update_crypto_key_primary_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = resources.CryptoKey( + name="name_value", + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", + rotation_period=duration_pb2.Duration(seconds=751), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKey.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.update_crypto_key_primary_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == "name_value" + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" + + +def test_update_crypto_key_primary_version_rest_required_fields( + request_type=service.UpdateCryptoKeyPrimaryVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["crypto_key_version_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 + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["cryptoKeyVersionId"] = "crypto_key_version_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "cryptoKeyVersionId" in jsonified_request + assert jsonified_request["cryptoKeyVersionId"] == "crypto_key_version_id_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKey.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.update_crypto_key_primary_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_crypto_key_primary_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_crypto_key_primary_version._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "cryptoKeyVersionId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_primary_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, + "post_update_crypto_key_primary_version", + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, + "pre_update_crypto_key_primary_version", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyPrimaryVersionRequest.pb( + service.UpdateCryptoKeyPrimaryVersionRequest() + ) + 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 = resources.CryptoKey.to_json(resources.CryptoKey()) + + request = service.UpdateCryptoKeyPrimaryVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.update_crypto_key_primary_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_primary_version_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCryptoKeyPrimaryVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.update_crypto_key_primary_version(request) + + +def test_update_crypto_key_primary_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + crypto_key_version_id="crypto_key_version_id_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 = resources.CryptoKey.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.update_crypto_key_primary_version(**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/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion" + % client.transport._host, + args[1], + ) + + +def test_update_crypto_key_primary_version_rest_flattened_error( + transport: str = "rest", +): + client = KeyManagementServiceClient( + 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_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name="name_value", + crypto_key_version_id="crypto_key_version_id_value", + ) + + +def test_update_crypto_key_primary_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DestroyCryptoKeyVersionRequest, + dict, + ], +) +def test_destroy_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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 = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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.destroy_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_destroy_crypto_key_version_rest_required_fields( + request_type=service.DestroyCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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() + ).destroy_crypto_key_version._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() + ).destroy_crypto_key_version._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKeyVersion.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.destroy_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_destroy_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.destroy_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_destroy_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, + "post_destroy_crypto_key_version", + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_destroy_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DestroyCryptoKeyVersionRequest.pb( + service.DestroyCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.DestroyCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.destroy_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_destroy_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.DestroyCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.destroy_crypto_key_version(request) + + +def test_destroy_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # 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 = resources.CryptoKeyVersion.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.destroy_crypto_key_version(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy" + % client.transport._host, + args[1], + ) + + +def test_destroy_crypto_key_version_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name="name_value", + ) + + +def test_destroy_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.RestoreCryptoKeyVersionRequest, + dict, + ], +) +def test_restore_crypto_key_version_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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 = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CryptoKeyVersion.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.restore_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.reimport_eligible is True + + +def test_restore_crypto_key_version_rest_required_fields( + request_type=service.RestoreCryptoKeyVersionRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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() + ).restore_crypto_key_version._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() + ).restore_crypto_key_version._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CryptoKeyVersion.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.restore_crypto_key_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, + "post_restore_crypto_key_version", + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_restore_crypto_key_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreCryptoKeyVersionRequest.pb( + service.RestoreCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json( + resources.CryptoKeyVersion() + ) + + request = service.RestoreCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.restore_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_crypto_key_version_rest_bad_request( + transport: str = "rest", request_type=service.RestoreCryptoKeyVersionRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.restore_crypto_key_version(request) + + +def test_restore_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + 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 = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # 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 = resources.CryptoKeyVersion.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.restore_crypto_key_version(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_crypto_key_version_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name="name_value", + ) + + +def test_restore_crypto_key_version_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.EncryptRequest, + dict, + ], +) +def test_encrypt_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = service.EncryptResponse( + name="name_value", + ciphertext=b"ciphertext_blob", + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.EncryptResponse.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.encrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == "name_value" + assert response.ciphertext == b"ciphertext_blob" + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_encrypt_rest_required_fields(request_type=service.EncryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["plaintext"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["plaintext"] = b"plaintext_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "plaintext" in jsonified_request + assert jsonified_request["plaintext"] == b"plaintext_blob" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.EncryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.EncryptResponse.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.encrypt(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_encrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.encrypt._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "plaintext", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_encrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_encrypt" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_encrypt" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.EncryptRequest.pb(service.EncryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.EncryptResponse.to_json( + service.EncryptResponse() + ) + + request = service.EncryptRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.EncryptResponse() + + client.encrypt( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_encrypt_rest_bad_request( + transport: str = "rest", request_type=service.EncryptRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.encrypt(request) + + +def test_encrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.EncryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + plaintext=b"plaintext_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.EncryptResponse.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.encrypt(**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/*/keyRings/*/cryptoKeys/**}:encrypt" + % client.transport._host, + args[1], + ) + + +def test_encrypt_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.encrypt( + service.EncryptRequest(), + name="name_value", + plaintext=b"plaintext_blob", + ) + + +def test_encrypt_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DecryptRequest, + dict, + ], +) +def test_decrypt_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = service.DecryptResponse( + plaintext=b"plaintext_blob", + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.DecryptResponse.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.decrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b"plaintext_blob" + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_decrypt_rest_required_fields(request_type=service.DecryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ciphertext"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["ciphertext"] = b"ciphertext_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "ciphertext" in jsonified_request + assert jsonified_request["ciphertext"] == b"ciphertext_blob" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.DecryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.DecryptResponse.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.decrypt(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_decrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.decrypt._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "ciphertext", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_decrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_decrypt" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_decrypt" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DecryptRequest.pb(service.DecryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.DecryptResponse.to_json( + service.DecryptResponse() + ) + + request = service.DecryptRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.DecryptResponse() + + client.decrypt( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_decrypt_rest_bad_request( + transport: str = "rest", request_type=service.DecryptRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.decrypt(request) + + +def test_decrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.DecryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ciphertext=b"ciphertext_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.DecryptResponse.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.decrypt(**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/*/keyRings/*/cryptoKeys/*}:decrypt" + % client.transport._host, + args[1], + ) + + +def test_decrypt_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.decrypt( + service.DecryptRequest(), + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + +def test_decrypt_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.AsymmetricSignRequest, + dict, + ], +) +def test_asymmetric_sign_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse( + signature=b"signature_blob", + verified_digest_crc32c=True, + name="name_value", + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.AsymmetricSignResponse.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.asymmetric_sign(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b"signature_blob" + assert response.verified_digest_crc32c is True + assert response.name == "name_value" + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_asymmetric_sign_rest_required_fields( + request_type=service.AsymmetricSignRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + 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() + ).asymmetric_sign._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() + ).asymmetric_sign._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.AsymmetricSignResponse.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.asymmetric_sign(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_asymmetric_sign_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.asymmetric_sign._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_asymmetric_sign_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_asymmetric_sign" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_sign" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.AsymmetricSignRequest.pb(service.AsymmetricSignRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.AsymmetricSignResponse.to_json( + service.AsymmetricSignResponse() + ) + + request = service.AsymmetricSignRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AsymmetricSignResponse() + + client.asymmetric_sign( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_asymmetric_sign_rest_bad_request( + transport: str = "rest", request_type=service.AsymmetricSignRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.asymmetric_sign(request) + + +def test_asymmetric_sign_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + digest=service.Digest(sha256=b"sha256_blob"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.AsymmetricSignResponse.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.asymmetric_sign(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign" + % client.transport._host, + args[1], + ) + + +def test_asymmetric_sign_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.asymmetric_sign( + service.AsymmetricSignRequest(), + name="name_value", + digest=service.Digest(sha256=b"sha256_blob"), + ) + + +def test_asymmetric_sign_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.AsymmetricDecryptRequest, + dict, + ], +) +def test_asymmetric_decrypt_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse( + plaintext=b"plaintext_blob", + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.AsymmetricDecryptResponse.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.asymmetric_decrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b"plaintext_blob" + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_asymmetric_decrypt_rest_required_fields( + request_type=service.AsymmetricDecryptRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ciphertext"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).asymmetric_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["ciphertext"] = b"ciphertext_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).asymmetric_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "ciphertext" in jsonified_request + assert jsonified_request["ciphertext"] == b"ciphertext_blob" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.AsymmetricDecryptResponse.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.asymmetric_decrypt(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_asymmetric_decrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.asymmetric_decrypt._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "ciphertext", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_asymmetric_decrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_asymmetric_decrypt" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_decrypt" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.AsymmetricDecryptRequest.pb( + service.AsymmetricDecryptRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.AsymmetricDecryptResponse.to_json( + service.AsymmetricDecryptResponse() + ) + + request = service.AsymmetricDecryptRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AsymmetricDecryptResponse() + + client.asymmetric_decrypt( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_asymmetric_decrypt_rest_bad_request( + transport: str = "rest", request_type=service.AsymmetricDecryptRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.asymmetric_decrypt(request) + + +def test_asymmetric_decrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ciphertext=b"ciphertext_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.AsymmetricDecryptResponse.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.asymmetric_decrypt(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt" + % client.transport._host, + args[1], + ) + + +def test_asymmetric_decrypt_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + +def test_asymmetric_decrypt_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.MacSignRequest, + dict, + ], +) +def test_mac_sign_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse( + name="name_value", + mac=b"mac_blob", + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.MacSignResponse.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.mac_sign(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == "name_value" + assert response.mac == b"mac_blob" + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_mac_sign_rest_required_fields(request_type=service.MacSignRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["data"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).mac_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["data"] = b"data_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).mac_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "data" in jsonified_request + assert jsonified_request["data"] == b"data_blob" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.MacSignResponse.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.mac_sign(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_mac_sign_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.mac_sign._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "data", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mac_sign_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_mac_sign" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_mac_sign" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.MacSignRequest.pb(service.MacSignRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.MacSignResponse.to_json( + service.MacSignResponse() + ) + + request = service.MacSignRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.MacSignResponse() + + client.mac_sign( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mac_sign_rest_bad_request( + transport: str = "rest", request_type=service.MacSignRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.mac_sign(request) + + +def test_mac_sign_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + data=b"data_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.MacSignResponse.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.mac_sign(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign" + % client.transport._host, + args[1], + ) + + +def test_mac_sign_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.mac_sign( + service.MacSignRequest(), + name="name_value", + data=b"data_blob", + ) + + +def test_mac_sign_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.MacVerifyRequest, + dict, + ], +) +def test_mac_verify_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse( + name="name_value", + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.MacVerifyResponse.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.mac_verify(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == "name_value" + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_mac_verify_rest_required_fields(request_type=service.MacVerifyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["data"] = b"" + request_init["mac"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).mac_verify._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["data"] = b"data_blob" + jsonified_request["mac"] = b"mac_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).mac_verify._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "data" in jsonified_request + assert jsonified_request["data"] == b"data_blob" + assert "mac" in jsonified_request + assert jsonified_request["mac"] == b"mac_blob" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.MacVerifyResponse.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.mac_verify(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_mac_verify_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.mac_verify._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "data", + "mac", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mac_verify_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_mac_verify" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_mac_verify" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.MacVerifyRequest.pb(service.MacVerifyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.MacVerifyResponse.to_json( + service.MacVerifyResponse() + ) + + request = service.MacVerifyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.MacVerifyResponse() + + client.mac_verify( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mac_verify_rest_bad_request( + transport: str = "rest", request_type=service.MacVerifyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.mac_verify(request) + + +def test_mac_verify_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.MacVerifyResponse.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.mac_verify(**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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify" + % client.transport._host, + args[1], + ) + + +def test_mac_verify_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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.mac_verify( + service.MacVerifyRequest(), + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + + +def test_mac_verify_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateRandomBytesRequest, + dict, + ], +) +def test_generate_random_bytes_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateRandomBytesResponse( + data=b"data_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.GenerateRandomBytesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.generate_random_bytes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b"data_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_random_bytes_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, "post_generate_random_bytes" + ) as post, mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_generate_random_bytes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateRandomBytesRequest.pb( + service.GenerateRandomBytesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.GenerateRandomBytesResponse.to_json( + service.GenerateRandomBytesResponse() + ) + + request = service.GenerateRandomBytesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateRandomBytesResponse() + + client.generate_random_bytes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_random_bytes_rest_bad_request( + transport: str = "rest", request_type=service.GenerateRandomBytesRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "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.generate_random_bytes(request) + + +def test_generate_random_bytes_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateRandomBytesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.GenerateRandomBytesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.generate_random_bytes(**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/{location=projects/*/locations/*}:generateRandomBytes" + % client.transport._host, + args[1], + ) + + +def test_generate_random_bytes_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +def test_generate_random_bytes_rest_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + 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 = KeyManagementServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = KeyManagementServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + transports.KeyManagementServiceRestTransport, + ], +) +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 = KeyManagementServiceClient.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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.KeyManagementServiceGrpcTransport, + ) + + +def test_key_management_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_key_management_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_key_rings", + "list_crypto_keys", + "list_crypto_key_versions", + "list_import_jobs", + "get_key_ring", + "get_crypto_key", + "get_crypto_key_version", + "get_public_key", + "get_import_job", + "create_key_ring", + "create_crypto_key", + "create_crypto_key_version", + "import_crypto_key_version", + "create_import_job", + "update_crypto_key", + "update_crypto_key_version", + "update_crypto_key_primary_version", + "destroy_crypto_key_version", + "restore_crypto_key_version", + "encrypt", + "decrypt", + "asymmetric_sign", + "asymmetric_decrypt", + "mac_sign", + "mac_verify", + "generate_random_bytes", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_key_management_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +def test_key_management_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport() + adc.assert_called_once() + + +def test_key_management_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KeyManagementServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + transports.KeyManagementServiceRestTransport, + ], +) +def test_key_management_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KeyManagementServiceGrpcTransport, grpc_helpers), + (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_key_management_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_key_management_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.KeyManagementServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_key_management_service_host_no_port(transport_name): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_key_management_service_host_with_port(transport_name): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudkms.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudkms.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_key_management_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = KeyManagementServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = KeyManagementServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_key_rings._session + session2 = client2.transport.list_key_rings._session + assert session1 != session2 + session1 = client1.transport.list_crypto_keys._session + session2 = client2.transport.list_crypto_keys._session + assert session1 != session2 + session1 = client1.transport.list_crypto_key_versions._session + session2 = client2.transport.list_crypto_key_versions._session + assert session1 != session2 + session1 = client1.transport.list_import_jobs._session + session2 = client2.transport.list_import_jobs._session + assert session1 != session2 + session1 = client1.transport.get_key_ring._session + session2 = client2.transport.get_key_ring._session + assert session1 != session2 + session1 = client1.transport.get_crypto_key._session + session2 = client2.transport.get_crypto_key._session + assert session1 != session2 + session1 = client1.transport.get_crypto_key_version._session + session2 = client2.transport.get_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.get_public_key._session + session2 = client2.transport.get_public_key._session + assert session1 != session2 + session1 = client1.transport.get_import_job._session + session2 = client2.transport.get_import_job._session + assert session1 != session2 + session1 = client1.transport.create_key_ring._session + session2 = client2.transport.create_key_ring._session + assert session1 != session2 + session1 = client1.transport.create_crypto_key._session + session2 = client2.transport.create_crypto_key._session + assert session1 != session2 + session1 = client1.transport.create_crypto_key_version._session + session2 = client2.transport.create_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.import_crypto_key_version._session + session2 = client2.transport.import_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.create_import_job._session + session2 = client2.transport.create_import_job._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key._session + session2 = client2.transport.update_crypto_key._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key_version._session + session2 = client2.transport.update_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key_primary_version._session + session2 = client2.transport.update_crypto_key_primary_version._session + assert session1 != session2 + session1 = client1.transport.destroy_crypto_key_version._session + session2 = client2.transport.destroy_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.restore_crypto_key_version._session + session2 = client2.transport.restore_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.encrypt._session + session2 = client2.transport.encrypt._session + assert session1 != session2 + session1 = client1.transport.decrypt._session + session2 = client2.transport.decrypt._session + assert session1 != session2 + session1 = client1.transport.asymmetric_sign._session + session2 = client2.transport.asymmetric_sign._session + assert session1 != session2 + session1 = client1.transport.asymmetric_decrypt._session + session2 = client2.transport.asymmetric_decrypt._session + assert session1 != session2 + session1 = client1.transport.mac_sign._session + session2 = client2.transport.mac_sign._session + assert session1 != session2 + session1 = client1.transport.mac_verify._session + session2 = client2.transport.mac_verify._session + assert session1 != session2 + session1 = client1.transport.generate_random_bytes._session + session2 = client2.transport.generate_random_bytes._session + assert session1 != session2 + + +def test_key_management_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_key_management_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_crypto_key_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = KeyManagementServiceClient.crypto_key_path( + project, location, key_ring, crypto_key + ) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = KeyManagementServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = KeyManagementServiceClient.crypto_key_version_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) + assert expected == actual + + +def test_import_job_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + import_job = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format( + project=project, + location=location, + key_ring=key_ring, + import_job=import_job, + ) + actual = KeyManagementServiceClient.import_job_path( + project, location, key_ring, import_job + ) + assert expected == actual + + +def test_parse_import_job_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "import_job": "clam", + } + path = KeyManagementServiceClient.import_job_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_import_job_path(path) + assert expected == actual + + +def test_key_ring_path(): + project = "whelk" + location = "octopus" + key_ring = "oyster" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format( + project=project, + location=location, + key_ring=key_ring, + ) + actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) + assert expected == actual + + +def test_parse_key_ring_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "key_ring": "mussel", + } + path = KeyManagementServiceClient.key_ring_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_key_ring_path(path) + assert expected == actual + + +def test_public_key_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = KeyManagementServiceClient.public_key_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_public_key_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.public_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_public_key_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = KeyManagementServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = KeyManagementServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = KeyManagementServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = KeyManagementServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = KeyManagementServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = KeyManagementServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = KeyManagementServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = KeyManagementServiceClient.common_project_path(**expected) -@pytest.mark.parametrize( - "transport_class", - [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -def test_key_management_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - quota_project_id="octopus", - ) + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_project_path(path) + assert expected == actual -@pytest.mark.parametrize( - "transport_class", - [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -def test_key_management_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = KeyManagementServiceClient.common_location_path(project, location) + assert expected == actual -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KeyManagementServiceGrpcTransport, grpc_helpers), - (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_key_management_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = KeyManagementServiceClient.common_location_path(**expected) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloudkms", - ), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_location_path(path) + assert expected == actual -@pytest.mark.parametrize( - "transport_class", - [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -def test_key_management_service_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + with mock.patch.object( + transports.KeyManagementServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.KeyManagementServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = KeyManagementServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) + prep.assert_called_once_with(client_info) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_key_management_service_host_no_port(transport_name): +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudkms.googleapis.com" - ), - transport=transport_name, + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - assert client.transport._host == ("cloudkms.googleapis.com:443") + + # 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( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + locations_pb2.GetLocationRequest, + dict, ], ) -def test_key_management_service_host_with_port(transport_name): +def test_get_location_rest(request_type): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudkms.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("cloudkms.googleapis.com:8000") + 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) -def test_key_management_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + response = client.get_location(request) + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_key_management_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + + 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) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, + locations_pb2.ListLocationsRequest, + dict, ], ) -def test_key_management_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_list_locations_rest(request_type): + client = KeyManagementServiceClient( + 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) + - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request + ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, + iam_policy_pb2.GetIamPolicyRequest, + dict, ], ) -def test_key_management_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() +def test_get_iam_policy_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) -def test_crypto_key_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( - project=project, - location=location, - key_ring=key_ring, - crypto_key=crypto_key, + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = KeyManagementServiceClient.crypto_key_path( - project, location, key_ring, crypto_key + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request ) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) -def test_parse_crypto_key_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "crypto_key": "mussel", - } - path = KeyManagementServiceClient.crypto_key_path(**expected) - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_crypto_key_version_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( - project=project, - location=location, - key_ring=key_ring, - crypto_key=crypto_key, - crypto_key_version=crypto_key_version, + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = KeyManagementServiceClient.crypto_key_version_path( - project, location, key_ring, crypto_key, crypto_key_version + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/keyRings/sample3"}, request ) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) -def test_parse_crypto_key_version_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.crypto_key_version_path(**expected) - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/keyRings/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 = iam_policy_pb2.TestIamPermissionsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_import_job_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - import_job = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format( - project=project, - location=location, - key_ring=key_ring, - import_job=import_job, - ) - actual = KeyManagementServiceClient.import_job_path( - project, location, key_ring, import_job + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_list_locations(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() -def test_parse_import_job_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "import_job": "clam", - } - path = KeyManagementServiceClient.import_job_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_import_job_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_key_ring_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format( - project=project, - location=location, - key_ring=key_ring, +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() -def test_parse_key_ring_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - } - path = KeyManagementServiceClient.key_ring_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_key_ring_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_public_key_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format( - project=project, - location=location, - key_ring=key_ring, - crypto_key=crypto_key, - crypto_key_version=crypto_key_version, - ) - actual = KeyManagementServiceClient.public_key_path( - project, location, key_ring, crypto_key, crypto_key_version +def test_list_locations_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_public_key_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.public_key_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_public_key_path(path) - assert expected == actual + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = KeyManagementServiceClient.common_billing_account_path(billing_account) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = KeyManagementServiceClient.common_billing_account_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_billing_account_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format( - folder=folder, +def test_list_locations_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = KeyManagementServiceClient.common_folder_path(folder) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = KeyManagementServiceClient.common_folder_path(**expected) - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_folder_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format( - organization=organization, +def test_get_location(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = KeyManagementServiceClient.common_organization_path(organization) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = KeyManagementServiceClient.common_organization_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_organization_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format( - project=project, +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = KeyManagementServiceClient.common_project_path(project) - assert expected == actual + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = KeyManagementServiceClient.common_project_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_project_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +def test_get_location_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials() ) - actual = KeyManagementServiceClient.common_location_path(project, location) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = KeyManagementServiceClient.common_location_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_location_path(path) - assert expected == actual + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) - with mock.patch.object( - transports.KeyManagementServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() ) - prep.assert_called_once_with(client_info) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - with mock.patch.object( - transports.KeyManagementServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = KeyManagementServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } ) - prep.assert_called_once_with(client_info) + call.assert_called() @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_get_location_from_dict_async(): client = KeyManagementServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() def test_set_iam_policy(transport: str = "grpc"): @@ -9505,6 +18276,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -9522,6 +18294,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: