From 7750b02b41ec307359c7e79070b82e016728aea0 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 12 May 2023 13:02:22 -0400 Subject: [PATCH] feat: added VerifyConnectivity RPC (#388) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: added VerifyConnectivity RPC PiperOrigin-RevId: 530991686 Source-Link: https://github.com/googleapis/googleapis/commit/be2600ed6ce9f63ceb9db0bda82e385575f59446 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7eadc0e0aaece2bccb4e561f3b29b0584fbcf906 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2VhZGMwZTBhYWVjZTJiY2NiNGU1NjFmM2IyOWIwNTg0ZmJjZjkwNiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../google/cloud/kms/__init__.py | 4 + .../google/cloud/kms_v1/__init__.py | 4 + .../google/cloud/kms_v1/gapic_metadata.json | 15 + .../services/ekm_service/async_client.py | 110 ++++ .../kms_v1/services/ekm_service/client.py | 110 ++++ .../services/ekm_service/transports/base.py | 17 + .../services/ekm_service/transports/grpc.py | 34 ++ .../ekm_service/transports/grpc_asyncio.py | 35 ++ .../services/ekm_service/transports/rest.py | 132 +++++ .../google/cloud/kms_v1/types/__init__.py | 4 + .../google/cloud/kms_v1/types/ekm_service.py | 26 + ...d_ekm_service_verify_connectivity_async.py | 52 ++ ...ed_ekm_service_verify_connectivity_sync.py | 52 ++ .../snippet_metadata_google.cloud.kms.v1.json | 163 +++++- .../scripts/fixup_kms_v1_keywords.py | 1 + .../unit/gapic/kms_v1/test_ekm_service.py | 511 ++++++++++++++++++ 16 files changed, 1269 insertions(+), 1 deletion(-) create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py create mode 100644 packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py diff --git a/packages/google-cloud-kms/google/cloud/kms/__init__.py b/packages/google-cloud-kms/google/cloud/kms/__init__.py index 295aed2b7461..6e58f0057fff 100644 --- a/packages/google-cloud-kms/google/cloud/kms/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms/__init__.py @@ -37,6 +37,8 @@ ListEkmConnectionsResponse, UpdateEkmConfigRequest, UpdateEkmConnectionRequest, + VerifyConnectivityRequest, + VerifyConnectivityResponse, ) from google.cloud.kms_v1.types.resources import ( CryptoKey, @@ -106,6 +108,8 @@ "ListEkmConnectionsResponse", "UpdateEkmConfigRequest", "UpdateEkmConnectionRequest", + "VerifyConnectivityRequest", + "VerifyConnectivityResponse", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py index 6f89ec6c22cf..bcb823b37780 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py @@ -34,6 +34,8 @@ ListEkmConnectionsResponse, UpdateEkmConfigRequest, UpdateEkmConnectionRequest, + VerifyConnectivityRequest, + VerifyConnectivityResponse, ) from .types.resources import ( CryptoKey, @@ -151,4 +153,6 @@ "UpdateCryptoKeyVersionRequest", "UpdateEkmConfigRequest", "UpdateEkmConnectionRequest", + "VerifyConnectivityRequest", + "VerifyConnectivityResponse", ) 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 613eb4880464..4e2e98425fd1 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 @@ -39,6 +39,11 @@ "methods": [ "update_ekm_connection" ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] } } }, @@ -74,6 +79,11 @@ "methods": [ "update_ekm_connection" ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] } } }, @@ -109,6 +119,11 @@ "methods": [ "update_ekm_connection" ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] } } } 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 d6cf2361c515..e0f88584102d 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 @@ -990,6 +990,116 @@ async def sample_update_ekm_config(): # Done; return the response. return response + async def verify_connectivity( + self, + request: Optional[Union[ekm_service.VerifyConnectivityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = await client.verify_connectivity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]]): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = ekm_service.VerifyConnectivityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.verify_connectivity, + 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 get_location( self, request: Optional[locations_pb2.GetLocationRequest] = 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 c5098fa746ee..5298274a840a 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 @@ -1222,6 +1222,116 @@ def sample_update_ekm_config(): # Done; return the response. return response + def verify_connectivity( + self, + request: Optional[Union[ekm_service.VerifyConnectivityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = client.verify_connectivity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + name (str): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.VerifyConnectivityRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.VerifyConnectivityRequest): + request = ekm_service.VerifyConnectivityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.verify_connectivity] + + # 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 __enter__(self) -> "EkmServiceClient": return self 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 4c4724048bb3..8e049bc42c5e 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 @@ -198,6 +198,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.verify_connectivity: gapic_v1.method.wrap_method( + self.verify_connectivity, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -266,6 +271,18 @@ def update_ekm_config( ]: raise NotImplementedError() + @property + def verify_connectivity( + self, + ) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + Union[ + ekm_service.VerifyConnectivityResponse, + Awaitable[ekm_service.VerifyConnectivityResponse], + ], + ]: + raise NotImplementedError() + @property def get_location( 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 952197d3dce7..54d9e06bad47 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 @@ -399,6 +399,40 @@ def update_ekm_config( ) return self._stubs["update_ekm_config"] + @property + def verify_connectivity( + self, + ) -> Callable[ + [ekm_service.VerifyConnectivityRequest], ekm_service.VerifyConnectivityResponse + ]: + r"""Return a callable for the verify connectivity method over gRPC. + + Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + Returns: + Callable[[~.VerifyConnectivityRequest], + ~.VerifyConnectivityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # 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 "verify_connectivity" not in self._stubs: + self._stubs["verify_connectivity"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/VerifyConnectivity", + request_serializer=ekm_service.VerifyConnectivityRequest.serialize, + response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, + ) + return self._stubs["verify_connectivity"] + @property def set_iam_policy( self, 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 9b87d3ae71db..18b794fa4db5 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 @@ -411,6 +411,41 @@ def update_ekm_config( ) return self._stubs["update_ekm_config"] + @property + def verify_connectivity( + self, + ) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + Awaitable[ekm_service.VerifyConnectivityResponse], + ]: + r"""Return a callable for the verify connectivity method over gRPC. + + Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + Returns: + Callable[[~.VerifyConnectivityRequest], + Awaitable[~.VerifyConnectivityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # 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 "verify_connectivity" not in self._stubs: + self._stubs["verify_connectivity"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/VerifyConnectivity", + request_serializer=ekm_service.VerifyConnectivityRequest.serialize, + response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, + ) + return self._stubs["verify_connectivity"] + @property def set_iam_policy( self, 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 index ff30398a55a1..79327e0b1006 100644 --- 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 @@ -117,6 +117,14 @@ def post_update_ekm_connection(self, response): logging.log(f"Received response: {response}") return response + def pre_verify_connectivity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_verify_connectivity(self, response): + logging.log(f"Received response: {response}") + return response + transport = EkmServiceRestTransport(interceptor=MyCustomEkmServiceInterceptor()) client = EkmServiceClient(transport=transport) @@ -261,6 +269,29 @@ def post_update_ekm_connection( """ return response + def pre_verify_connectivity( + self, + request: ekm_service.VerifyConnectivityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_service.VerifyConnectivityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for verify_connectivity + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_verify_connectivity( + self, response: ekm_service.VerifyConnectivityResponse + ) -> ekm_service.VerifyConnectivityResponse: + """Post-rpc interceptor for verify_connectivity + + 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, @@ -1097,6 +1128,97 @@ def __call__( resp = self._interceptor.post_update_ekm_connection(resp) return resp + class _VerifyConnectivity(EkmServiceRestStub): + def __hash__(self): + return hash("VerifyConnectivity") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: ekm_service.VerifyConnectivityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Call the verify connectivity method over HTTP. + + Args: + request (~.ekm_service.VerifyConnectivityRequest): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + 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.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/ekmConnections/*}:verifyConnectivity", + }, + ] + request, metadata = self._interceptor.pre_verify_connectivity( + request, metadata + ) + pb_request = ekm_service.VerifyConnectivityRequest.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.VerifyConnectivityResponse() + pb_resp = ekm_service.VerifyConnectivityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_verify_connectivity(resp) + return resp + @property def create_ekm_connection( self, @@ -1147,6 +1269,16 @@ def update_ekm_connection( # In C++ this would require a dynamic_cast return self._UpdateEkmConnection(self._session, self._host, self._interceptor) # type: ignore + @property + def verify_connectivity( + self, + ) -> Callable[ + [ekm_service.VerifyConnectivityRequest], ekm_service.VerifyConnectivityResponse + ]: + # 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._VerifyConnectivity(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py index 35d730b92327..183a8fcf4d34 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py @@ -24,6 +24,8 @@ ListEkmConnectionsResponse, UpdateEkmConfigRequest, UpdateEkmConnectionRequest, + VerifyConnectivityRequest, + VerifyConnectivityResponse, ) from .resources import ( CryptoKey, @@ -89,6 +91,8 @@ "ListEkmConnectionsResponse", "UpdateEkmConfigRequest", "UpdateEkmConnectionRequest", + "VerifyConnectivityRequest", + "VerifyConnectivityResponse", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/ekm_service.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/ekm_service.py index 3a7f07201757..99af57dead99 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/ekm_service.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/ekm_service.py @@ -34,6 +34,8 @@ "Certificate", "EkmConnection", "EkmConfig", + "VerifyConnectivityRequest", + "VerifyConnectivityResponse", }, ) @@ -523,4 +525,28 @@ class EkmConfig(proto.Message): ) +class VerifyConnectivityRequest(proto.Message): + r"""Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConnection.name] + of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class VerifyConnectivityResponse(proto.Message): + r"""Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py new file mode 100644 index 000000000000..cc5e0817998c --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py @@ -0,0 +1,52 @@ +# -*- 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConnectivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = await client.verify_connectivity(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py new file mode 100644 index 000000000000..139e27d2266f --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py @@ -0,0 +1,52 @@ +# -*- 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConnectivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = client.verify_connectivity(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index f59bbd3d8f95..76f786e8bb76 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-kms", - "version": "2.16.1" + "version": "0.1.0" }, "snippets": [ { @@ -1009,6 +1009,167 @@ ], "title": "cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.verify_connectivity", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "VerifyConnectivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.VerifyConnectivityResponse", + "shortName": "verify_connectivity" + }, + "description": "Sample for VerifyConnectivity", + "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.verify_connectivity", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "VerifyConnectivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.VerifyConnectivityResponse", + "shortName": "verify_connectivity" + }, + "description": "Sample for VerifyConnectivity", + "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-kms/scripts/fixup_kms_v1_keywords.py b/packages/google-cloud-kms/scripts/fixup_kms_v1_keywords.py index fa31e4f633b3..02cf7ba47aa5 100644 --- a/packages/google-cloud-kms/scripts/fixup_kms_v1_keywords.py +++ b/packages/google-cloud-kms/scripts/fixup_kms_v1_keywords.py @@ -71,6 +71,7 @@ class kmsCallTransformer(cst.CSTTransformer): 'update_crypto_key_version': ('crypto_key_version', 'update_mask', ), 'update_ekm_config': ('ekm_config', 'update_mask', ), 'update_ekm_connection': ('ekm_connection', 'update_mask', ), + 'verify_connectivity': ('name', ), 'get_iam_policy': ('resource', 'options', ), 'set_iam_policy': ('resource', 'policy', ), 'test_iam_permissions': ('resource', 'permissions', ), 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 a61974d87d39..b8f93dcb1ed7 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 @@ -2452,6 +2452,246 @@ async def test_update_ekm_config_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + ekm_service.VerifyConnectivityRequest, + dict, + ], +) +def test_verify_connectivity(request_type, transport: str = "grpc"): + client = EkmServiceClient( + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse() + response = client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.VerifyConnectivityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +def test_verify_connectivity_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), "__call__" + ) as call: + client.verify_connectivity() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.VerifyConnectivityRequest() + + +@pytest.mark.asyncio +async def test_verify_connectivity_async( + transport: str = "grpc_asyncio", request_type=ekm_service.VerifyConnectivityRequest +): + 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 = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.VerifyConnectivityResponse() + ) + response = await client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.VerifyConnectivityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +@pytest.mark.asyncio +async def test_verify_connectivity_async_from_dict(): + await test_verify_connectivity_async(request_type=dict) + + +def test_verify_connectivity_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 = ekm_service.VerifyConnectivityRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), "__call__" + ) as call: + call.return_value = ekm_service.VerifyConnectivityResponse() + client.verify_connectivity(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=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_verify_connectivity_field_headers_async(): + client = EkmServiceAsyncClient( + 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 = ekm_service.VerifyConnectivityRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.VerifyConnectivityResponse() + ) + await client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, 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=name_value", + ) in kw["metadata"] + + +def test_verify_connectivity_flattened(): + 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.verify_connectivity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.verify_connectivity( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_verify_connectivity_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_verify_connectivity_flattened_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.verify_connectivity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.VerifyConnectivityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.verify_connectivity( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_verify_connectivity_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ @@ -4361,6 +4601,273 @@ def test_update_ekm_config_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + ekm_service.VerifyConnectivityRequest, + dict, + ], +) +def test_verify_connectivity_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # 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.VerifyConnectivityResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = ekm_service.VerifyConnectivityResponse.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.verify_connectivity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +def test_verify_connectivity_rest_required_fields( + request_type=ekm_service.VerifyConnectivityRequest, +): + 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() + ).verify_connectivity._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() + ).verify_connectivity._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 = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.VerifyConnectivityResponse() + # 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.VerifyConnectivityResponse.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.verify_connectivity(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_verify_connectivity_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.verify_connectivity._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_verify_connectivity_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_verify_connectivity" + ) as post, mock.patch.object( + transports.EkmServiceRestInterceptor, "pre_verify_connectivity" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.VerifyConnectivityRequest.pb( + ekm_service.VerifyConnectivityRequest() + ) + 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.VerifyConnectivityResponse.to_json( + ekm_service.VerifyConnectivityResponse() + ) + + request = ekm_service.VerifyConnectivityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.VerifyConnectivityResponse() + + client.verify_connectivity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_verify_connectivity_rest_bad_request( + transport: str = "rest", request_type=ekm_service.VerifyConnectivityRequest +): + 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.verify_connectivity(request) + + +def test_verify_connectivity_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.VerifyConnectivityResponse() + + # 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.VerifyConnectivityResponse.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.verify_connectivity(**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/*}:verifyConnectivity" + % client.transport._host, + args[1], + ) + + +def test_verify_connectivity_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.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name="name_value", + ) + + +def test_verify_connectivity_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( @@ -4506,6 +5013,7 @@ def test_ekm_service_base_transport(): "update_ekm_connection", "get_ekm_config", "update_ekm_config", + "verify_connectivity", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -4796,6 +5304,9 @@ def test_ekm_service_client_transport_session_collision(transport_name): session1 = client1.transport.update_ekm_config._session session2 = client2.transport.update_ekm_config._session assert session1 != session2 + session1 = client1.transport.verify_connectivity._session + session2 = client2.transport.verify_connectivity._session + assert session1 != session2 def test_ekm_service_grpc_transport_channel():