From f7caff39d44bd3537c1ff44c3469a56e4e0d587b Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 19 Feb 2023 06:32:45 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#225) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: Add service_yaml_parameters to py_gapic_library BUILD.bazel targets PiperOrigin-RevId: 510187992 Source-Link: https://github.com/googleapis/googleapis/commit/5edc23561778df80d5293f20132765f8757a6b2c Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0bedb72e4765a3e0b674a28c50ea0f9a9b26a89 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBiZWRiNzJlNDc2NWEzZTBiNjc0YTI4YzUwZWEwZjlhOWIyNmE4OSJ9 * 🦉 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 --- packages/google-cloud-gke-hub/.coveragerc | 4 +- .../cloud/gkehub_v1/gapic_metadata.json | 60 + .../gkehub_v1/services/gke_hub/client.py | 2 + .../services/gke_hub/transports/__init__.py | 4 + .../services/gke_hub/transports/rest.py | 1628 +++++++ .../cloud/gkehub_v1beta1/gapic_metadata.json | 45 + .../gke_hub_membership_service/client.py | 2 + .../transports/__init__.py | 7 + .../transports/rest.py | 2148 +++++++++ .../unit/gapic/gkehub_v1/test_gke_hub.py | 3257 ++++++++++++- .../test_gke_hub_membership_service.py | 4163 ++++++++++++++--- 11 files changed, 10663 insertions(+), 657 deletions(-) create mode 100644 packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py create mode 100644 packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py diff --git a/packages/google-cloud-gke-hub/.coveragerc b/packages/google-cloud-gke-hub/.coveragerc index 2653a96bbb70..29f755733abb 100644 --- a/packages/google-cloud-gke-hub/.coveragerc +++ b/packages/google-cloud-gke-hub/.coveragerc @@ -4,8 +4,8 @@ branch = True [report] show_missing = True omit = - google/cloud/gkehub/__init__.py - google/cloud/gkehub/gapic_version.py + google/cloud/gkehub/multiclusteringress/__init__.py + google/cloud/gkehub/multiclusteringress/gapic_version.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json index 5086eae0decf..042eb2e45e32 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json @@ -126,6 +126,66 @@ ] } } + }, + "rest": { + "libraryClient": "GkeHubClient", + "rpcs": { + "CreateFeature": { + "methods": [ + "create_feature" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteFeature": { + "methods": [ + "delete_feature" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GetFeature": { + "methods": [ + "get_feature" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListFeatures": { + "methods": [ + "list_features" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateFeature": { + "methods": [ + "update_feature" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + } + } } } } diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py index 81385fdaa82d..97daaff29d8a 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py @@ -58,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, GkeHubTransport from .transports.grpc import GkeHubGrpcTransport from .transports.grpc_asyncio import GkeHubGrpcAsyncIOTransport +from .transports.rest import GkeHubRestTransport class GkeHubClientMeta(type): @@ -71,6 +72,7 @@ class GkeHubClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[GkeHubTransport]] _transport_registry["grpc"] = GkeHubGrpcTransport _transport_registry["grpc_asyncio"] = GkeHubGrpcAsyncIOTransport + _transport_registry["rest"] = GkeHubRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py index d4a25a6c3ea4..d2561ed33659 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py @@ -19,14 +19,18 @@ from .base import GkeHubTransport from .grpc import GkeHubGrpcTransport from .grpc_asyncio import GkeHubGrpcAsyncIOTransport +from .rest import GkeHubRestInterceptor, GkeHubRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[GkeHubTransport]] _transport_registry["grpc"] = GkeHubGrpcTransport _transport_registry["grpc_asyncio"] = GkeHubGrpcAsyncIOTransport +_transport_registry["rest"] = GkeHubRestTransport __all__ = ( "GkeHubTransport", "GkeHubGrpcTransport", "GkeHubGrpcAsyncIOTransport", + "GkeHubRestTransport", + "GkeHubRestInterceptor", ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py new file mode 100644 index 000000000000..cd75236faef8 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py @@ -0,0 +1,1628 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.gkehub_v1.types import feature, membership, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import GkeHubTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class GkeHubRestInterceptor: + """Interceptor for GkeHub. + + 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 GkeHubRestTransport. + + .. code-block:: python + class MyCustomGkeHubInterceptor(GkeHubRestInterceptor): + def pre_create_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_connect_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_connect_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_features(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_features(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GkeHubRestTransport(interceptor=MyCustomGkeHubInterceptor()) + client = GkeHubClient(transport=transport) + + + """ + + def pre_create_feature( + self, request: service.CreateFeatureRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.CreateFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_create_feature( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_create_membership( + self, + request: service.CreateMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_create_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_delete_feature( + self, request: service.DeleteFeatureRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.DeleteFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_delete_feature( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_delete_membership( + self, + request: service.DeleteMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_delete_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_generate_connect_manifest( + self, + request: service.GenerateConnectManifestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GenerateConnectManifestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_generate_connect_manifest( + self, response: service.GenerateConnectManifestResponse + ) -> service.GenerateConnectManifestResponse: + """Post-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_get_feature( + self, request: service.GetFeatureRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_feature(self, response: feature.Feature) -> feature.Feature: + """Post-rpc interceptor for get_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_get_membership( + self, request: service.GetMembershipRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_membership( + self, response: membership.Membership + ) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_list_features( + self, request: service.ListFeaturesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListFeaturesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_features + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_features( + self, response: service.ListFeaturesResponse + ) -> service.ListFeaturesResponse: + """Post-rpc interceptor for list_features + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_list_memberships( + self, + request: service.ListMembershipsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_memberships( + self, response: service.ListMembershipsResponse + ) -> service.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_update_feature( + self, request: service.UpdateFeatureRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.UpdateFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_feature( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + def pre_update_membership( + self, + request: service.UpdateMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GkeHubRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GkeHubRestInterceptor + + +class GkeHubRestTransport(GkeHubTransport): + """REST backend transport for GkeHub. + + The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently only available in the global region. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + 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 = "gkehub.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[GkeHubRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GkeHubRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateFeature(GkeHubRestStub): + def __hash__(self): + return hash("CreateFeature") + + def __call__( + self, + request: service.CreateFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create feature method over HTTP. + + Args: + request (~.service.CreateFeatureRequest): + The request object. Request message for the ``GkeHub.CreateFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/features", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_create_feature(request, metadata) + pb_request = service.CreateFeatureRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_feature(resp) + return resp + + class _CreateMembership(GkeHubRestStub): + def __hash__(self): + return hash("CreateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "membershipId": "", + } + + @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.CreateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create membership method over HTTP. + + Args: + request (~.service.CreateMembershipRequest): + The request object. Request message for the ``GkeHub.CreateMembership`` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/memberships", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_create_membership( + request, metadata + ) + pb_request = service.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _DeleteFeature(GkeHubRestStub): + def __hash__(self): + return hash("DeleteFeature") + + def __call__( + self, + request: service.DeleteFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete feature method over HTTP. + + Args: + request (~.service.DeleteFeatureRequest): + The request object. Request message for ``GkeHub.DeleteFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_feature(request, metadata) + pb_request = service.DeleteFeatureRequest.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["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_feature(resp) + return resp + + class _DeleteMembership(GkeHubRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __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.DeleteMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete membership method over HTTP. + + Args: + request (~.service.DeleteMembershipRequest): + The request object. Request message for ``GkeHub.DeleteMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_membership( + request, metadata + ) + pb_request = service.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _GenerateConnectManifest(GkeHubRestStub): + def __hash__(self): + return hash("GenerateConnectManifest") + + __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.GenerateConnectManifestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateConnectManifestResponse: + r"""Call the generate connect manifest method over HTTP. + + Args: + request (~.service.GenerateConnectManifestRequest): + The request object. Request message for ``GkeHub.GenerateConnectManifest`` + method. . + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest", + }, + ] + request, metadata = self._interceptor.pre_generate_connect_manifest( + request, metadata + ) + pb_request = service.GenerateConnectManifestRequest.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.GenerateConnectManifestResponse() + pb_resp = service.GenerateConnectManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_connect_manifest(resp) + return resp + + class _GetFeature(GkeHubRestStub): + def __hash__(self): + return hash("GetFeature") + + def __call__( + self, + request: service.GetFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> feature.Feature: + r"""Call the get feature method over HTTP. + + Args: + request (~.service.GetFeatureRequest): + The request object. Request message for ``GkeHub.GetFeature`` 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: + ~.feature.Feature: + Feature represents the settings and + status of any Hub Feature. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + }, + ] + request, metadata = self._interceptor.pre_get_feature(request, metadata) + pb_request = service.GetFeatureRequest.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["$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 = feature.Feature() + pb_resp = feature.Feature.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_feature(resp) + return resp + + class _GetMembership(GkeHubRestStub): + def __hash__(self): + return hash("GetMembership") + + __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.GetMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.service.GetMembershipRequest): + The request object. Request message for ``GkeHub.GetMembership`` 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: + ~.membership.Membership: + Membership contains information about + a member cluster. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = service.GetMembershipRequest.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 = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _ListFeatures(GkeHubRestStub): + def __hash__(self): + return hash("ListFeatures") + + def __call__( + self, + request: service.ListFeaturesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListFeaturesResponse: + r"""Call the list features method over HTTP. + + Args: + request (~.service.ListFeaturesRequest): + The request object. Request message for ``GkeHub.ListFeatures`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListFeaturesResponse: + Response message for the ``GkeHub.ListFeatures`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/features", + }, + ] + request, metadata = self._interceptor.pre_list_features(request, metadata) + pb_request = service.ListFeaturesRequest.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["$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.ListFeaturesResponse() + pb_resp = service.ListFeaturesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_features(resp) + return resp + + class _ListMemberships(GkeHubRestStub): + def __hash__(self): + return hash("ListMemberships") + + __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.ListMembershipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.service.ListMembershipsRequest): + The request object. Request message for ``GkeHub.ListMemberships`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListMembershipsResponse: + Response message for the ``GkeHub.ListMemberships`` + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/memberships", + }, + ] + request, metadata = self._interceptor.pre_list_memberships( + request, metadata + ) + pb_request = service.ListMembershipsRequest.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.ListMembershipsResponse() + pb_resp = service.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _UpdateFeature(GkeHubRestStub): + def __hash__(self): + return hash("UpdateFeature") + + def __call__( + self, + request: service.UpdateFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update feature method over HTTP. + + Args: + request (~.service.UpdateFeatureRequest): + The request object. Request message for ``GkeHub.UpdateFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_update_feature(request, metadata) + pb_request = service.UpdateFeatureRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_feature(resp) + return resp + + class _UpdateMembership(GkeHubRestStub): + def __hash__(self): + return hash("UpdateMembership") + + __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.UpdateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update membership method over HTTP. + + Args: + request (~.service.UpdateMembershipRequest): + The request object. Request message for ``GkeHub.UpdateMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_update_membership( + request, metadata + ) + pb_request = service.UpdateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_membership(resp) + return resp + + @property + def create_feature( + self, + ) -> Callable[[service.CreateFeatureRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_membership( + self, + ) -> Callable[[service.CreateMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_feature( + self, + ) -> Callable[[service.DeleteFeatureRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership( + self, + ) -> Callable[[service.DeleteMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_connect_manifest( + self, + ) -> Callable[ + [service.GenerateConnectManifestRequest], + service.GenerateConnectManifestResponse, + ]: + # 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._GenerateConnectManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_feature(self) -> Callable[[service.GetFeatureRequest], feature.Feature]: + # 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._GetFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership( + self, + ) -> Callable[[service.GetMembershipRequest], membership.Membership]: + # 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._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_features( + self, + ) -> Callable[[service.ListFeaturesRequest], service.ListFeaturesResponse]: + # 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._ListFeatures(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships( + self, + ) -> Callable[[service.ListMembershipsRequest], service.ListMembershipsResponse]: + # 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._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_feature( + self, + ) -> Callable[[service.UpdateFeatureRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership( + self, + ) -> Callable[[service.UpdateMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("GkeHubRestTransport",) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_metadata.json b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_metadata.json index 9f0aee44b79c..5cfc89c97cec 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_metadata.json @@ -96,6 +96,51 @@ ] } } + }, + "rest": { + "libraryClient": "GkeHubMembershipServiceClient", + "rpcs": { + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GenerateExclusivityManifest": { + "methods": [ + "generate_exclusivity_manifest" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "ValidateExclusivity": { + "methods": [ + "validate_exclusivity" + ] + } + } } } } diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py index af185dc6dda0..318ed0d87748 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py @@ -63,6 +63,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, GkeHubMembershipServiceTransport from .transports.grpc import GkeHubMembershipServiceGrpcTransport from .transports.grpc_asyncio import GkeHubMembershipServiceGrpcAsyncIOTransport +from .transports.rest import GkeHubMembershipServiceRestTransport class GkeHubMembershipServiceClientMeta(type): @@ -78,6 +79,7 @@ class GkeHubMembershipServiceClientMeta(type): ) # type: Dict[str, Type[GkeHubMembershipServiceTransport]] _transport_registry["grpc"] = GkeHubMembershipServiceGrpcTransport _transport_registry["grpc_asyncio"] = GkeHubMembershipServiceGrpcAsyncIOTransport + _transport_registry["rest"] = GkeHubMembershipServiceRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py index 742fa3ae8615..9aa0b430f1d3 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py @@ -19,6 +19,10 @@ from .base import GkeHubMembershipServiceTransport from .grpc import GkeHubMembershipServiceGrpcTransport from .grpc_asyncio import GkeHubMembershipServiceGrpcAsyncIOTransport +from .rest import ( + GkeHubMembershipServiceRestInterceptor, + GkeHubMembershipServiceRestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[GkeHubMembershipServiceTransport]] _transport_registry["grpc"] = GkeHubMembershipServiceGrpcTransport _transport_registry["grpc_asyncio"] = GkeHubMembershipServiceGrpcAsyncIOTransport +_transport_registry["rest"] = GkeHubMembershipServiceRestTransport __all__ = ( "GkeHubMembershipServiceTransport", "GkeHubMembershipServiceGrpcTransport", "GkeHubMembershipServiceGrpcAsyncIOTransport", + "GkeHubMembershipServiceRestTransport", + "GkeHubMembershipServiceRestInterceptor", ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py new file mode 100644 index 000000000000..f70014a9326d --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py @@ -0,0 +1,2148 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.gkehub_v1beta1.types import membership + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import GkeHubMembershipServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class GkeHubMembershipServiceRestInterceptor: + """Interceptor for GkeHubMembershipService. + + 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 GkeHubMembershipServiceRestTransport. + + .. code-block:: python + class MyCustomGkeHubMembershipServiceInterceptor(GkeHubMembershipServiceRestInterceptor): + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_connect_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_connect_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_exclusivity_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_exclusivity_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_exclusivity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_exclusivity(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GkeHubMembershipServiceRestTransport(interceptor=MyCustomGkeHubMembershipServiceInterceptor()) + client = GkeHubMembershipServiceClient(transport=transport) + + + """ + + def pre_create_membership( + self, + request: membership.CreateMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_create_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_delete_membership( + self, + request: membership.DeleteMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_delete_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_generate_connect_manifest( + self, + request: membership.GenerateConnectManifestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.GenerateConnectManifestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_generate_connect_manifest( + self, response: membership.GenerateConnectManifestResponse + ) -> membership.GenerateConnectManifestResponse: + """Post-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_generate_exclusivity_manifest( + self, + request: membership.GenerateExclusivityManifestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + membership.GenerateExclusivityManifestRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for generate_exclusivity_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_generate_exclusivity_manifest( + self, response: membership.GenerateExclusivityManifestResponse + ) -> membership.GenerateExclusivityManifestResponse: + """Post-rpc interceptor for generate_exclusivity_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_get_membership( + self, + request: membership.GetMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_get_membership( + self, response: membership.Membership + ) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_list_memberships( + self, + request: membership.ListMembershipsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_list_memberships( + self, response: membership.ListMembershipsResponse + ) -> membership.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_update_membership( + self, + request: membership.UpdateMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.UpdateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_update_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_validate_exclusivity( + self, + request: membership.ValidateExclusivityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.ValidateExclusivityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_exclusivity + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_validate_exclusivity( + self, response: membership.ValidateExclusivityResponse + ) -> membership.ValidateExclusivityResponse: + """Post-rpc interceptor for validate_exclusivity + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: operations_pb2.CancelOperationRequest + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> None: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_delete_operation( + self, response: operations_pb2.DeleteOperationRequest + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.Operation: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.GetOperationRequest + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> operations_pb2.ListOperationsResponse: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsRequest + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GkeHubMembershipServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GkeHubMembershipServiceRestInterceptor + + +class GkeHubMembershipServiceRestTransport(GkeHubMembershipServiceTransport): + """REST backend transport for GkeHubMembershipService. + + The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently only available in the global region. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + 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 = "gkehub.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[GkeHubMembershipServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GkeHubMembershipServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("CreateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "membershipId": "", + } + + @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: membership.CreateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create membership method over HTTP. + + Args: + request (~.membership.CreateMembershipRequest): + The request object. Request message for the + ``GkeHubMembershipService.CreateMembership`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/memberships", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_create_membership( + request, metadata + ) + pb_request = membership.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _DeleteMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __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: membership.DeleteMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete membership method over HTTP. + + Args: + request (~.membership.DeleteMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.DeleteMembership`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/memberships/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_membership( + request, metadata + ) + pb_request = membership.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _GenerateConnectManifest(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GenerateConnectManifest") + + __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: membership.GenerateConnectManifestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateConnectManifestResponse: + r"""Call the generate connect manifest method over HTTP. + + Args: + request (~.membership.GenerateConnectManifestRequest): + The request object. Request message for + ``GkeHubMembershipService.GenerateConnectManifest`` + 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: + ~.membership.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest", + }, + ] + request, metadata = self._interceptor.pre_generate_connect_manifest( + request, metadata + ) + pb_request = membership.GenerateConnectManifestRequest.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 = membership.GenerateConnectManifestResponse() + pb_resp = membership.GenerateConnectManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_connect_manifest(resp) + return resp + + class _GenerateExclusivityManifest(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GenerateExclusivityManifest") + + __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: membership.GenerateExclusivityManifestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateExclusivityManifestResponse: + r"""Call the generate exclusivity + manifest method over HTTP. + + Args: + request (~.membership.GenerateExclusivityManifestRequest): + The request object. The request to generate the manifests + for exclusivity artifacts. + + 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: + ~.membership.GenerateExclusivityManifestResponse: + The response of the exclusivity + artifacts manifests for the client to + apply. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/memberships/*}:generateExclusivityManifest", + }, + ] + request, metadata = self._interceptor.pre_generate_exclusivity_manifest( + request, metadata + ) + pb_request = membership.GenerateExclusivityManifestRequest.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 = membership.GenerateExclusivityManifestResponse() + pb_resp = membership.GenerateExclusivityManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_exclusivity_manifest(resp) + return resp + + class _GetMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GetMembership") + + __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: membership.GetMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.membership.GetMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.GetMembership`` 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: + ~.membership.Membership: + Membership contains information about + a member cluster. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/memberships/*}", + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = membership.GetMembershipRequest.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 = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _ListMemberships(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("ListMemberships") + + __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: membership.ListMembershipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.membership.ListMembershipsRequest): + The request object. Request message for + ``GkeHubMembershipService.ListMemberships`` 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: + ~.membership.ListMembershipsResponse: + Response message for the + ``GkeHubMembershipService.ListMemberships`` method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/memberships", + }, + ] + request, metadata = self._interceptor.pre_list_memberships( + request, metadata + ) + pb_request = membership.ListMembershipsRequest.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 = membership.ListMembershipsResponse() + pb_resp = membership.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _UpdateMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("UpdateMembership") + + __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: membership.UpdateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update membership method over HTTP. + + Args: + request (~.membership.UpdateMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.UpdateMembership`` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{name=projects/*/locations/*/memberships/*}", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_update_membership( + request, metadata + ) + pb_request = membership.UpdateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_membership(resp) + return resp + + class _ValidateExclusivity(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("ValidateExclusivity") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "intendedMembership": "", + } + + @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: membership.ValidateExclusivityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.ValidateExclusivityResponse: + r"""Call the validate exclusivity method over HTTP. + + Args: + request (~.membership.ValidateExclusivityRequest): + The request object. The request to validate the existing + state of the membership CR in the + cluster. + + 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: + ~.membership.ValidateExclusivityResponse: + The response of exclusivity artifacts + validation result status. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/memberships:validateExclusivity", + }, + ] + request, metadata = self._interceptor.pre_validate_exclusivity( + request, metadata + ) + pb_request = membership.ValidateExclusivityRequest.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 = membership.ValidateExclusivityResponse() + pb_resp = membership.ValidateExclusivityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_exclusivity(resp) + return resp + + @property + def create_membership( + self, + ) -> Callable[[membership.CreateMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership( + self, + ) -> Callable[[membership.DeleteMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_connect_manifest( + self, + ) -> Callable[ + [membership.GenerateConnectManifestRequest], + membership.GenerateConnectManifestResponse, + ]: + # 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._GenerateConnectManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_exclusivity_manifest( + self, + ) -> Callable[ + [membership.GenerateExclusivityManifestRequest], + membership.GenerateExclusivityManifestResponse, + ]: + # 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._GenerateExclusivityManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership( + self, + ) -> Callable[[membership.GetMembershipRequest], membership.Membership]: + # 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._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships( + self, + ) -> Callable[ + [membership.ListMembershipsRequest], membership.ListMembershipsResponse + ]: + # 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._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership( + self, + ) -> Callable[[membership.UpdateMembershipRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_exclusivity( + self, + ) -> Callable[ + [membership.ValidateExclusivityRequest], membership.ValidateExclusivityResponse + ]: + # 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._ValidateExclusivity(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(GkeHubMembershipServiceRestStub): + 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": "/v1beta1/{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(GkeHubMembershipServiceRestStub): + 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": "/v1beta1/{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(GkeHubMembershipServiceRestStub): + 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": "/v1beta1/{resource=projects/*/locations/*/memberships/*}: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(GkeHubMembershipServiceRestStub): + 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": "/v1beta1/{resource=projects/*/locations/*/memberships/*}: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(GkeHubMembershipServiceRestStub): + 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": "/v1beta1/{resource=projects/*/locations/*/memberships/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(GkeHubMembershipServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(GkeHubMembershipServiceRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(GkeHubMembershipServiceRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(GkeHubMembershipServiceRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("GkeHubMembershipServiceRestTransport",) diff --git a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py index c39791d9fd18..33260581093b 100644 --- a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py +++ b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.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 ( @@ -43,12 +45,15 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.gkehub_v1 import configmanagement_v1 # type: ignore from google.cloud.gkehub_v1 import multiclusteringress_v1 # type: ignore @@ -104,6 +109,7 @@ def test__get_default_mtls_endpoint(): [ (GkeHubClient, "grpc"), (GkeHubAsyncClient, "grpc_asyncio"), + (GkeHubClient, "rest"), ], ) def test_gke_hub_client_from_service_account_info(client_class, transport_name): @@ -117,7 +123,11 @@ def test_gke_hub_client_from_service_account_info(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("gkehub.googleapis.com:443") + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) @pytest.mark.parametrize( @@ -125,6 +135,7 @@ def test_gke_hub_client_from_service_account_info(client_class, transport_name): [ (transports.GkeHubGrpcTransport, "grpc"), (transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GkeHubRestTransport, "rest"), ], ) def test_gke_hub_client_service_account_always_use_jwt(transport_class, transport_name): @@ -148,6 +159,7 @@ def test_gke_hub_client_service_account_always_use_jwt(transport_class, transpor [ (GkeHubClient, "grpc"), (GkeHubAsyncClient, "grpc_asyncio"), + (GkeHubClient, "rest"), ], ) def test_gke_hub_client_from_service_account_file(client_class, transport_name): @@ -168,13 +180,18 @@ def test_gke_hub_client_from_service_account_file(client_class, transport_name): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("gkehub.googleapis.com:443") + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) def test_gke_hub_client_get_transport_class(): transport = GkeHubClient.get_transport_class() available_transports = [ transports.GkeHubGrpcTransport, + transports.GkeHubRestTransport, ] assert transport in available_transports @@ -187,6 +204,7 @@ def test_gke_hub_client_get_transport_class(): [ (GkeHubClient, transports.GkeHubGrpcTransport, "grpc"), (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubClient, transports.GkeHubRestTransport, "rest"), ], ) @mock.patch.object( @@ -326,6 +344,8 @@ def test_gke_hub_client_client_options(client_class, transport_class, transport_ "grpc_asyncio", "false", ), + (GkeHubClient, transports.GkeHubRestTransport, "rest", "true"), + (GkeHubClient, transports.GkeHubRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -511,6 +531,7 @@ def test_gke_hub_client_get_mtls_endpoint_and_cert_source(client_class): [ (GkeHubClient, transports.GkeHubGrpcTransport, "grpc"), (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubClient, transports.GkeHubRestTransport, "rest"), ], ) def test_gke_hub_client_client_options_scopes( @@ -546,6 +567,7 @@ def test_gke_hub_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (GkeHubClient, transports.GkeHubRestTransport, "rest", None), ], ) def test_gke_hub_client_client_options_credentials_file( @@ -3666,171 +3688,3075 @@ async def test_generate_connect_manifest_field_headers_async(): ) in kw["metadata"] -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.GkeHubGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipsRequest, + dict, + ], +) +def test_list_memberships_rest(request_type): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = GkeHubClient( - 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.ListMembershipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.GkeHubGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListMembershipsResponse.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_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_memberships_rest_required_fields( + request_type=service.ListMembershipsRequest, +): + transport_class = transports.GkeHubRestTransport + + 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, + ) ) - with pytest.raises(ValueError): - client = GkeHubClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_memberships._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_memberships._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) - # It is an error to provide an api_key and a transport instance. - transport = transports.GkeHubGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse() + # 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.ListMembershipsResponse.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_memberships(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GkeHubClient( - client_options=options, - transport=transport, + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(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.GkeHubRestInterceptor, "post_list_memberships" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_memberships" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListMembershipsRequest.pb(service.ListMembershipsRequest()) + 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.ListMembershipsResponse.to_json( + service.ListMembershipsResponse() ) - # 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 = GkeHubClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = service.ListMembershipsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListMembershipsResponse() + + client.list_memberships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.GkeHubGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request( + transport: str = "rest", request_type=service.ListMembershipsRequest +): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = GkeHubClient( - 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.GkeHubGrpcTransport( + # 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_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = GkeHubClient(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.ListMembershipsResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GkeHubGrpcTransport( + # 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.ListMembershipsResponse.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_memberships(**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/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_list_memberships_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.GkeHubGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memberships( + service.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_rest_pager(transport: str = "rest"): + client = GkeHubClient( 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.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + service.ListMembershipsResponse( + resources=[], + next_page_token="def", + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubGrpcTransport, - transports.GkeHubGrpcAsyncIOTransport, - ], -) -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() + # Wrap the values into proper Response objs + response = tuple(service.ListMembershipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(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.ListFeaturesRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = GkeHubClient.get_transport_class(transport_name)( +def test_list_features_rest(request_type): + client = GkeHubClient( 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"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = GkeHubClient( + # 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.ListFeaturesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListFeaturesResponse.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_features(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFeaturesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_features_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), ) - assert isinstance( - client.transport, - transports.GkeHubGrpcTransport, - ) + client = GkeHubClient(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.GkeHubRestInterceptor, "post_list_features" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_features" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListFeaturesRequest.pb(service.ListFeaturesRequest()) + 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.ListFeaturesResponse.to_json( + service.ListFeaturesResponse() + ) + request = service.ListFeaturesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListFeaturesResponse() -def test_gke_hub_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.GkeHubTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + client.list_features( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_gke_hub_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.GkeHubTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_memberships", - "list_features", - "get_membership", - "get_feature", - "create_membership", - "create_feature", - "delete_membership", - "delete_feature", - "update_membership", - "update_feature", - "generate_connect_manifest", +def test_list_features_rest_bad_request( + transport: str = "rest", request_type=service.ListFeaturesRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # 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_features(request) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] + +def test_list_features_rest_flattened(): + client = GkeHubClient( + 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.ListFeaturesResponse() + + # 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.ListFeaturesResponse.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_features(**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/*}/features" % client.transport._host, + args[1], + ) + + +def test_list_features_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_features( + service.ListFeaturesRequest(), + parent="parent_value", + ) + + +def test_list_features_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListFeaturesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_features(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, feature.Feature) for i in results) + + pages = list(client.list_features(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.GetMembershipRequest, + dict, + ], +) +def test_get_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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 = membership.Membership( + name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.Membership.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_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.external_id == "external_id_value" + assert response.unique_id == "unique_id_value" + + +def test_get_membership_rest_required_fields(request_type=service.GetMembershipRequest): + transport_class = transports.GkeHubRestTransport + + 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_membership._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_membership._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # 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 = membership.Membership.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_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(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.GkeHubRestInterceptor, "post_get_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetMembershipRequest.pb(service.GetMembershipRequest()) + 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 = membership.Membership.to_json( + membership.Membership() + ) + + request = service.GetMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.get_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_membership_rest_bad_request( + transport: str = "rest", request_type=service.GetMembershipRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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_membership(request) + + +def test_get_membership_rest_flattened(): + client = GkeHubClient( + 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 = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/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 = membership.Membership.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_membership(**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/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_get_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_membership( + service.GetMembershipRequest(), + name="name_value", + ) + + +def test_get_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetFeatureRequest, + dict, + ], +) +def test_get_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/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 = feature.Feature( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = feature.Feature.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_feature(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, feature.Feature) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(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.GkeHubRestInterceptor, "post_get_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetFeatureRequest.pb(service.GetFeatureRequest()) + 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 = feature.Feature.to_json(feature.Feature()) + + request = service.GetFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = feature.Feature() + + client.get_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_feature_rest_bad_request( + transport: str = "rest", request_type=service.GetFeatureRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/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_feature(request) + + +def test_get_feature_rest_flattened(): + client = GkeHubClient( + 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 = feature.Feature() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/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 = feature.Feature.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_feature(**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/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_get_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_feature( + service.GetFeatureRequest(), + name="name_value", + ) + + +def test_get_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipRequest, + dict, + ], +) +def test_create_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_membership_rest_required_fields( + request_type=service.CreateMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_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 "membershipId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == request_init["membership_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["membershipId"] = "membership_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "membership_id", + "request_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 "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == "membership_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_membership(request) + + expected_params = [ + ( + "membershipId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "membershipId", + "requestId", + ) + ) + & set( + ( + "parent", + "membershipId", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateMembershipRequest.pb( + service.CreateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request( + transport: str = "rest", request_type=service.CreateMembershipRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + } + 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_membership(request) + + +def test_create_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_membership(**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/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_create_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_membership( + service.CreateMembershipRequest(), + parent="parent_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", + ) + + +def test_create_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateFeatureRequest, + dict, + ], +) +def test_create_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateFeatureRequest.pb(service.CreateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_feature_rest_bad_request( + transport: str = "rest", request_type=service.CreateFeatureRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + } + 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_feature(request) + + +def test_create_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_feature(**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/*}/features" % client.transport._host, + args[1], + ) + + +def test_create_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_feature( + service.CreateFeatureRequest(), + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", + ) + + +def test_create_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMembershipRequest, + dict, + ], +) +def test_delete_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_membership_rest_required_fields( + request_type=service.DeleteMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteMembershipRequest.pb( + service.DeleteMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DeleteMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request( + transport: str = "rest", request_type=service.DeleteMembershipRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_membership(**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/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + service.DeleteMembershipRequest(), + name="name_value", + ) + + +def test_delete_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteFeatureRequest, + dict, + ], +) +def test_delete_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteFeatureRequest.pb(service.DeleteFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DeleteFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_feature_rest_bad_request( + transport: str = "rest", request_type=service.DeleteFeatureRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_feature(request) + + +def test_delete_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_feature(**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/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_delete_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_feature( + service.DeleteFeatureRequest(), + name="name_value", + ) + + +def test_delete_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipRequest, + dict, + ], +) +def test_update_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_membership_rest_required_fields( + request_type=service.UpdateMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + 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() + ).update_membership._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() + ).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + 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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "name", + "updateMask", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateMembershipRequest.pb( + service.UpdateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_membership_rest_bad_request( + transport: str = "rest", request_type=service.UpdateMembershipRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + } + 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_membership(request) + + +def test_update_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_membership(**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/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_update_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_membership( + service.UpdateMembershipRequest(), + name="name_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateFeatureRequest, + dict, + ], +) +def test_update_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateFeatureRequest.pb(service.UpdateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_feature_rest_bad_request( + transport: str = "rest", request_type=service.UpdateFeatureRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + } + 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_feature(request) + + +def test_update_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_feature(**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/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_update_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + 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_feature( + service.UpdateFeatureRequest(), + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateConnectManifestRequest, + dict, + ], +) +def test_generate_connect_manifest_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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.GenerateConnectManifestResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.GenerateConnectManifestResponse.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_connect_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_rest_required_fields( + request_type=service.GenerateConnectManifestRequest, +): + transport_class = transports.GkeHubRestTransport + + 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() + ).generate_connect_manifest._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() + ).generate_connect_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "image_pull_secret_content", + "is_upgrade", + "namespace", + "proxy", + "registry", + "version", + ) + ) + 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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateConnectManifestResponse() + # 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.GenerateConnectManifestResponse.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_connect_manifest(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_connect_manifest_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "imagePullSecretContent", + "isUpgrade", + "namespace", + "proxy", + "registry", + "version", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_connect_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(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.GkeHubRestInterceptor, "post_generate_connect_manifest" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_generate_connect_manifest" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateConnectManifestRequest.pb( + service.GenerateConnectManifestRequest() + ) + 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.GenerateConnectManifestResponse.to_json( + service.GenerateConnectManifestResponse() + ) + + request = service.GenerateConnectManifestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateConnectManifestResponse() + + client.generate_connect_manifest( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_connect_manifest_rest_bad_request( + transport: str = "rest", request_type=service.GenerateConnectManifestRequest +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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.generate_connect_manifest(request) + + +def test_generate_connect_manifest_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubClient( + 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 = GkeHubClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GkeHubClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GkeHubGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubGrpcTransport, + transports.GkeHubGrpcAsyncIOTransport, + transports.GkeHubRestTransport, + ], +) +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 = GkeHubClient.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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GkeHubGrpcTransport, + ) + + +def test_gke_hub_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GkeHubTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_gke_hub_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GkeHubTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_memberships", + "list_features", + "get_membership", + "get_feature", + "create_membership", + "create_feature", + "delete_membership", + "delete_feature", + "update_membership", + "update_feature", + "generate_connect_manifest", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] for r in remainder: with pytest.raises(NotImplementedError): getattr(transport, r)() @@ -3905,6 +6831,7 @@ def test_gke_hub_transport_auth_adc(transport_class): [ transports.GkeHubGrpcTransport, transports.GkeHubGrpcAsyncIOTransport, + transports.GkeHubRestTransport, ], ) def test_gke_hub_transport_auth_gdch_credentials(transport_class): @@ -3999,11 +6926,40 @@ def test_gke_hub_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_gke_hub_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.GkeHubRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_gke_hub_rest_lro_client(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_gke_hub_host_no_port(transport_name): @@ -4014,7 +6970,11 @@ def test_gke_hub_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("gkehub.googleapis.com:443") + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) @pytest.mark.parametrize( @@ -4022,6 +6982,7 @@ def test_gke_hub_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_gke_hub_host_with_port(transport_name): @@ -4032,7 +6993,63 @@ def test_gke_hub_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("gkehub.googleapis.com:8000") + assert client.transport._host == ( + "gkehub.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_gke_hub_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GkeHubClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GkeHubClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.list_features._session + session2 = client2.transport.list_features._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.get_feature._session + session2 = client2.transport.get_feature._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.create_feature._session + session2 = client2.transport.create_feature._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.delete_feature._session + session2 = client2.transport.delete_feature._session + assert session1 != session2 + session1 = client1.transport.update_membership._session + session2 = client2.transport.update_membership._session + assert session1 != session2 + session1 = client1.transport.update_feature._session + session2 = client2.transport.update_feature._session + assert session1 != session2 + session1 = client1.transport.generate_connect_manifest._session + session2 = client2.transport.generate_connect_manifest._session + assert session1 != session2 def test_gke_hub_grpc_transport_channel(): @@ -4383,6 +7400,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4400,6 +7418,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py index 1796f5c35b61..d6202b899892 100644 --- a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py +++ b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_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 ( @@ -47,6 +49,7 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore import grpc @@ -54,6 +57,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.gkehub_v1beta1.services.gke_hub_membership_service import ( GkeHubMembershipServiceAsyncClient, @@ -114,6 +119,7 @@ def test__get_default_mtls_endpoint(): [ (GkeHubMembershipServiceClient, "grpc"), (GkeHubMembershipServiceAsyncClient, "grpc_asyncio"), + (GkeHubMembershipServiceClient, "rest"), ], ) def test_gke_hub_membership_service_client_from_service_account_info( @@ -129,7 +135,11 @@ def test_gke_hub_membership_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("gkehub.googleapis.com:443") + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) @pytest.mark.parametrize( @@ -137,6 +147,7 @@ def test_gke_hub_membership_service_client_from_service_account_info( [ (transports.GkeHubMembershipServiceGrpcTransport, "grpc"), (transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GkeHubMembershipServiceRestTransport, "rest"), ], ) def test_gke_hub_membership_service_client_service_account_always_use_jwt( @@ -162,6 +173,7 @@ def test_gke_hub_membership_service_client_service_account_always_use_jwt( [ (GkeHubMembershipServiceClient, "grpc"), (GkeHubMembershipServiceAsyncClient, "grpc_asyncio"), + (GkeHubMembershipServiceClient, "rest"), ], ) def test_gke_hub_membership_service_client_from_service_account_file( @@ -184,13 +196,18 @@ def test_gke_hub_membership_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("gkehub.googleapis.com:443") + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) def test_gke_hub_membership_service_client_get_transport_class(): transport = GkeHubMembershipServiceClient.get_transport_class() available_transports = [ transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceRestTransport, ] assert transport in available_transports @@ -211,6 +228,11 @@ def test_gke_hub_membership_service_client_get_transport_class(): transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + GkeHubMembershipServiceClient, + transports.GkeHubMembershipServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -366,6 +388,18 @@ def test_gke_hub_membership_service_client_client_options( "grpc_asyncio", "false", ), + ( + GkeHubMembershipServiceClient, + transports.GkeHubMembershipServiceRestTransport, + "rest", + "true", + ), + ( + GkeHubMembershipServiceClient, + transports.GkeHubMembershipServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -571,6 +605,11 @@ def test_gke_hub_membership_service_client_get_mtls_endpoint_and_cert_source( transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + GkeHubMembershipServiceClient, + transports.GkeHubMembershipServiceRestTransport, + "rest", + ), ], ) def test_gke_hub_membership_service_client_client_options_scopes( @@ -611,6 +650,12 @@ def test_gke_hub_membership_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + GkeHubMembershipServiceClient, + transports.GkeHubMembershipServiceRestTransport, + "rest", + None, + ), ], ) def test_gke_hub_membership_service_client_client_options_credentials_file( @@ -2636,716 +2681,3760 @@ async def test_generate_exclusivity_manifest_field_headers_async(): ) in kw["metadata"] -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.GkeHubMembershipServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + membership.ListMembershipsRequest, + dict, + ], +) +def test_list_memberships_rest(request_type): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = GkeHubMembershipServiceClient( - 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 = membership.ListMembershipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.GkeHubMembershipServiceGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.ListMembershipsResponse.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_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_memberships_rest_required_fields( + request_type=membership.ListMembershipsRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + 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_memberships._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_memberships._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 = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + # 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 = membership.ListMembershipsResponse.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_memberships(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = GkeHubMembershipServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + unset_fields = transport.list_memberships._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.GkeHubMembershipServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GkeHubMembershipServiceClient( - client_options=options, - transport=transport, + client = GkeHubMembershipServiceClient(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.GkeHubMembershipServiceRestInterceptor, "post_list_memberships" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_list_memberships" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ListMembershipsRequest.pb( + membership.ListMembershipsRequest() + ) + 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 = membership.ListMembershipsResponse.to_json( + membership.ListMembershipsResponse() ) - # 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 = GkeHubMembershipServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = membership.ListMembershipsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ListMembershipsResponse() + + client.list_memberships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.GkeHubMembershipServiceGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request( + transport: str = "rest", request_type=membership.ListMembershipsRequest +): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = GkeHubMembershipServiceClient( - 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.GkeHubMembershipServiceGrpcTransport( + # 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_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = GkeHubMembershipServiceClient(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 = membership.ListMembershipsResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GkeHubMembershipServiceGrpcTransport( + # 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 = membership.ListMembershipsResponse.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_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_list_memberships_rest_flattened_error(transport: str = "rest"): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_rest_pager(transport: str = "rest"): + client = GkeHubMembershipServiceClient( 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 = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, - ], -) -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() + # Wrap the values into proper Response objs + response = tuple( + membership.ListMembershipsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(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", + membership.GetMembershipRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = GkeHubMembershipServiceClient.get_transport_class(transport_name)( +def test_get_membership_rest(request_type): + client = GkeHubMembershipServiceClient( 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/memberships/sample3"} + request = request_type(**request_init) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = GkeHubMembershipServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.GkeHubMembershipServiceGrpcTransport, + # 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 = membership.Membership( + name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", + infrastructure_type=membership.Membership.InfrastructureType.ON_PREM, + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.Membership.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_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.external_id == "external_id_value" + assert response.unique_id == "unique_id_value" + assert ( + response.infrastructure_type == membership.Membership.InfrastructureType.ON_PREM ) -def test_gke_hub_membership_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.GkeHubMembershipServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", +def test_get_membership_rest_required_fields( + request_type=membership.GetMembershipRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) + # verify fields with default values are dropped -def test_gke_hub_membership_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.GkeHubMembershipServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_memberships", - "get_membership", - "create_membership", - "delete_membership", - "update_membership", - "generate_connect_manifest", - "validate_exclusivity", - "generate_exclusivity_manifest", - "set_iam_policy", - "get_iam_policy", - "test_iam_permissions", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # verify required fields with default values are now present - with pytest.raises(NotImplementedError): - transport.close() + jsonified_request["name"] = "name_value" - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # 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 -def test_gke_hub_membership_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + pb_return_value = membership.Membership.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_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GkeHubMembershipServiceTransport( - 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.GkeHubMembershipServiceRestInterceptor, "post_get_membership" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_get_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GetMembershipRequest.pb( + membership.GetMembershipRequest() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + 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 = membership.Membership.to_json( + membership.Membership() ) + request = membership.GetMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() -def test_gke_hub_membership_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.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GkeHubMembershipServiceTransport() - adc.assert_called_once() + client.get_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() + post.assert_called_once() -def test_gke_hub_membership_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) - GkeHubMembershipServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, + +def test_get_membership_rest_bad_request( + transport: str = "rest", request_type=membership.GetMembershipRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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_membership(request) + + +def test_get_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + 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 = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/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 = membership.Membership.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 -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, - ], -) -def test_gke_hub_membership_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",), - quota_project_id="octopus", + client.get_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, - ], -) -def test_gke_hub_membership_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_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.GetMembershipRequest(), + name="name_value", + ) + + +def test_get_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.GkeHubMembershipServiceGrpcTransport, grpc_helpers), - (transports.GkeHubMembershipServiceGrpcAsyncIOTransport, grpc_helpers_async), + membership.CreateMembershipRequest, + dict, ], ) -def test_gke_hub_membership_service_transport_create_channel( - transport_class, grpc_helpers +def test_create_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "description": "description_value", + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "on_prem_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + "admin_cluster": True, + "cluster_type": 1, + }, + "multi_cloud_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "edge_cluster": {"resource_link": "resource_link_value"}, + "appliance_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "state": {"code": 1, "description": "description_value", "update_time": {}}, + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "infrastructure_type": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_membership_rest_required_fields( + request_type=membership.CreateMembershipRequest, ): - # If credentials and host are not provided, the transport class should use - # ADC credentials. + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_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 "membershipId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == request_init["membership_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["membershipId"] = "membership_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "membership_id", + "request_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 "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == "membership_id_value" + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_membership(request) + + expected_params = [ + ( + "membershipId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "membershipId", + "requestId", + ) + ) + & set( + ( + "parent", + "membershipId", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) 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"]) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "post_create_membership" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_create_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.CreateMembershipRequest.pb( + membership.CreateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - create_channel.assert_called_with( - "gkehub.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="gkehub.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), + request = membership.CreateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), ], ) + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request( + transport: str = "rest", request_type=membership.CreateMembershipRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "description": "description_value", + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "on_prem_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + "admin_cluster": True, + "cluster_type": 1, + }, + "multi_cloud_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "edge_cluster": {"resource_link": "resource_link_value"}, + "appliance_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "state": {"code": 1, "description": "description_value", "update_time": {}}, + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "infrastructure_type": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_membership(request) + + +def test_create_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource=membership.Membership(name="name_value"), + membership_id="membership_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_create_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.CreateMembershipRequest(), + parent="parent_value", + resource=membership.Membership(name="name_value"), + membership_id="membership_id_value", + ) + + +def test_create_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.DeleteMembershipRequest, + dict, + ], +) +def test_delete_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_membership_rest_required_fields( + request_type=membership.DeleteMembershipRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "post_delete_membership" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_delete_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.DeleteMembershipRequest.pb( + membership.DeleteMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = membership.DeleteMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request( + transport: str = "rest", request_type=membership.DeleteMembershipRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + membership.DeleteMembershipRequest(), + name="name_value", + ) + + +def test_delete_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.UpdateMembershipRequest, + dict, + ], +) +def test_update_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "description": "description_value", + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "on_prem_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + "admin_cluster": True, + "cluster_type": 1, + }, + "multi_cloud_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "edge_cluster": {"resource_link": "resource_link_value"}, + "appliance_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "state": {"code": 1, "description": "description_value", "update_time": {}}, + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "infrastructure_type": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_membership_rest_required_fields( + request_type=membership.UpdateMembershipRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + 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() + ).update_membership._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() + ).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "name", + "updateMask", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "post_update_membership" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_update_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.UpdateMembershipRequest.pb( + membership.UpdateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = membership.UpdateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_membership_rest_bad_request( + transport: str = "rest", request_type=membership.UpdateMembershipRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "description": "description_value", + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "on_prem_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + "admin_cluster": True, + "cluster_type": 1, + }, + "multi_cloud_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "edge_cluster": {"resource_link": "resource_link_value"}, + "appliance_cluster": {"resource_link": "resource_link_value"}, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + }, + }, + }, + "state": {"code": 1, "description": "description_value", "update_time": {}}, + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "infrastructure_type": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_membership(request) + + +def test_update_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + resource=membership.Membership(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_update_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.UpdateMembershipRequest(), + name="name_value", + resource=membership.Membership(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.GenerateConnectManifestRequest, + dict, + ], +) +def test_generate_connect_manifest_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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 = membership.GenerateConnectManifestResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.GenerateConnectManifestResponse.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_connect_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_rest_required_fields( + request_type=membership.GenerateConnectManifestRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + 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() + ).generate_connect_manifest._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() + ).generate_connect_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "connect_agent", + "image_pull_secret_content", + "is_upgrade", + "registry", + "version", + ) + ) + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.GenerateConnectManifestResponse() + # 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 = membership.GenerateConnectManifestResponse.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_connect_manifest(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_connect_manifest_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "connectAgent", + "imagePullSecretContent", + "isUpgrade", + "registry", + "version", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_connect_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(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.GkeHubMembershipServiceRestInterceptor, + "post_generate_connect_manifest", + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, + "pre_generate_connect_manifest", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GenerateConnectManifestRequest.pb( + membership.GenerateConnectManifestRequest() + ) + 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 = membership.GenerateConnectManifestResponse.to_json( + membership.GenerateConnectManifestResponse() + ) + + request = membership.GenerateConnectManifestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.GenerateConnectManifestResponse() + + client.generate_connect_manifest( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_connect_manifest_rest_bad_request( + transport: str = "rest", request_type=membership.GenerateConnectManifestRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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.generate_connect_manifest(request) + + +def test_generate_connect_manifest_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.ValidateExclusivityRequest, + dict, + ], +) +def test_validate_exclusivity_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.ValidateExclusivityResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.ValidateExclusivityResponse.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.validate_exclusivity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.ValidateExclusivityResponse) + + +def test_validate_exclusivity_rest_required_fields( + request_type=membership.ValidateExclusivityRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["intended_membership"] = "" + 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 "intendedMembership" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).validate_exclusivity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "intendedMembership" in jsonified_request + assert ( + jsonified_request["intendedMembership"] == request_init["intended_membership"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["intendedMembership"] = "intended_membership_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).validate_exclusivity._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cr_manifest", + "intended_membership", + ) + ) + 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 "intendedMembership" in jsonified_request + assert jsonified_request["intendedMembership"] == "intended_membership_value" + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ValidateExclusivityResponse() + # 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 = membership.ValidateExclusivityResponse.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.validate_exclusivity(request) + + expected_params = [ + ( + "intendedMembership", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_validate_exclusivity_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.validate_exclusivity._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "crManifest", + "intendedMembership", + ) + ) + & set( + ( + "parent", + "intendedMembership", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_exclusivity_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(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.GkeHubMembershipServiceRestInterceptor, "post_validate_exclusivity" + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, "pre_validate_exclusivity" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ValidateExclusivityRequest.pb( + membership.ValidateExclusivityRequest() + ) + 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 = membership.ValidateExclusivityResponse.to_json( + membership.ValidateExclusivityResponse() + ) + + request = membership.ValidateExclusivityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ValidateExclusivityResponse() + + client.validate_exclusivity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_validate_exclusivity_rest_bad_request( + transport: str = "rest", request_type=membership.ValidateExclusivityRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.validate_exclusivity(request) + + +def test_validate_exclusivity_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.GenerateExclusivityManifestRequest, + dict, + ], +) +def test_generate_exclusivity_manifest_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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 = membership.GenerateExclusivityManifestResponse( + crd_manifest="crd_manifest_value", + cr_manifest="cr_manifest_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = membership.GenerateExclusivityManifestResponse.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_exclusivity_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateExclusivityManifestResponse) + assert response.crd_manifest == "crd_manifest_value" + assert response.cr_manifest == "cr_manifest_value" + + +def test_generate_exclusivity_manifest_rest_required_fields( + request_type=membership.GenerateExclusivityManifestRequest, +): + transport_class = transports.GkeHubMembershipServiceRestTransport + + 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() + ).generate_exclusivity_manifest._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() + ).generate_exclusivity_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cr_manifest", + "crd_manifest", + ) + ) + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.GenerateExclusivityManifestResponse() + # 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 = membership.GenerateExclusivityManifestResponse.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_exclusivity_manifest(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_exclusivity_manifest_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_exclusivity_manifest._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "crManifest", + "crdManifest", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_exclusivity_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(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.GkeHubMembershipServiceRestInterceptor, + "post_generate_exclusivity_manifest", + ) as post, mock.patch.object( + transports.GkeHubMembershipServiceRestInterceptor, + "pre_generate_exclusivity_manifest", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GenerateExclusivityManifestRequest.pb( + membership.GenerateExclusivityManifestRequest() + ) + 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 = ( + membership.GenerateExclusivityManifestResponse.to_json( + membership.GenerateExclusivityManifestResponse() + ) + ) + + request = membership.GenerateExclusivityManifestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.GenerateExclusivityManifestResponse() + + client.generate_exclusivity_manifest( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_exclusivity_manifest_rest_bad_request( + transport: str = "rest", request_type=membership.GenerateExclusivityManifestRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/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.generate_exclusivity_manifest(request) + + +def test_generate_exclusivity_manifest_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + transports.GkeHubMembershipServiceRestTransport, + ], +) +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 = GkeHubMembershipServiceClient.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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GkeHubMembershipServiceGrpcTransport, + ) + + +def test_gke_hub_membership_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GkeHubMembershipServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_gke_hub_membership_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GkeHubMembershipServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_memberships", + "get_membership", + "create_membership", + "delete_membership", + "update_membership", + "generate_connect_manifest", + "validate_exclusivity", + "generate_exclusivity_manifest", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_gke_hub_membership_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.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubMembershipServiceTransport( + 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",), + quota_project_id="octopus", + ) + + +def test_gke_hub_membership_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.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubMembershipServiceTransport() + adc.assert_called_once() + + +def test_gke_hub_membership_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) + GkeHubMembershipServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + ], +) +def test_gke_hub_membership_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",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + transports.GkeHubMembershipServiceRestTransport, + ], +) +def test_gke_hub_membership_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.GkeHubMembershipServiceGrpcTransport, grpc_helpers), + (transports.GkeHubMembershipServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_gke_hub_membership_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( + "gkehub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="gkehub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + ], +) +def test_gke_hub_membership_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_gke_hub_membership_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.GkeHubMembershipServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_gke_hub_membership_service_rest_lro_client(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_gke_hub_membership_service_host_no_port(transport_name): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="gkehub.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "gkehub.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_gke_hub_membership_service_host_with_port(transport_name): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="gkehub.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "gkehub.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://gkehub.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_gke_hub_membership_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GkeHubMembershipServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GkeHubMembershipServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.update_membership._session + session2 = client2.transport.update_membership._session + assert session1 != session2 + session1 = client1.transport.generate_connect_manifest._session + session2 = client2.transport.generate_connect_manifest._session + assert session1 != session2 + session1 = client1.transport.validate_exclusivity._session + session2 = client2.transport.validate_exclusivity._session + assert session1 != session2 + session1 = client1.transport.generate_exclusivity_manifest._session + session2 = client2.transport.generate_exclusivity_manifest._session + assert session1 != session2 + + +def test_gke_hub_membership_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubMembershipServiceGrpcTransport( + 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_gke_hub_membership_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( + 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.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + ], +) +def test_gke_hub_membership_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.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + ], +) +def test_gke_hub_membership_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_gke_hub_membership_service_grpc_lro_client(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_gke_hub_membership_service_grpc_lro_async_client(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_membership_path(): + project = "squid" + location = "clam" + membership = "whelk" + expected = ( + "projects/{project}/locations/{location}/memberships/{membership}".format( + project=project, + location=location, + membership=membership, + ) + ) + actual = GkeHubMembershipServiceClient.membership_path( + project, location, membership + ) + assert expected == actual + + +def test_parse_membership_path(): + expected = { + "project": "octopus", + "location": "oyster", + "membership": "nudibranch", + } + path = GkeHubMembershipServiceClient.membership_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_membership_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = GkeHubMembershipServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = GkeHubMembershipServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = GkeHubMembershipServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = GkeHubMembershipServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = GkeHubMembershipServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = GkeHubMembershipServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = GkeHubMembershipServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = GkeHubMembershipServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = GkeHubMembershipServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = GkeHubMembershipServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.GkeHubMembershipServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.GkeHubMembershipServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = GkeHubMembershipServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, - ], -) -def test_gke_hub_membership_service_grpc_transport_client_cert_source_for_mtls( - transport_class, +@pytest.mark.asyncio +async def test_transport_close_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest ): - cred = ga_credentials.AnonymousCredentials() + client = GkeHubMembershipServiceClient( + 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( + {"name": "projects/sample1/locations/sample2"}, 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_location(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + locations_pb2.GetLocationRequest, + dict, ], ) -def test_gke_hub_membership_service_host_no_port(transport_name): +def test_get_location_rest(request_type): client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="gkehub.googleapis.com" - ), - transport=transport_name, + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert client.transport._host == ("gkehub.googleapis.com:443") + + 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_name", + "request_type", [ - "grpc", - "grpc_asyncio", + locations_pb2.ListLocationsRequest, + dict, ], ) -def test_gke_hub_membership_service_host_with_port(transport_name): +def test_list_locations_rest(request_type): client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="gkehub.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("gkehub.googleapis.com:8000") + 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) -def test_gke_hub_membership_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.GkeHubMembershipServiceGrpcTransport( - 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.list_locations(request) + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_gke_hub_membership_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = GkeHubMembershipServiceClient( + 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/memberships/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) -# 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.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + iam_policy_pb2.GetIamPolicyRequest, + dict, ], ) -def test_gke_hub_membership_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_get_iam_policy_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "resource": "projects/sample1/locations/sample2/memberships/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() - 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.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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/memberships/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.set_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.GkeHubMembershipServiceGrpcTransport, - transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + iam_policy_pb2.SetIamPolicyRequest, + dict, ], ) -def test_gke_hub_membership_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_set_iam_policy_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = { + "resource": "projects/sample1/locations/sample2/memberships/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() - 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 + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_gke_hub_membership_service_grpc_lro_client(): + 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 = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/memberships/sample3"}, request ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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_gke_hub_membership_service_grpc_lro_async_client(): - client = GkeHubMembershipServiceAsyncClient( +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - transport = client.transport + request_init = { + "resource": "projects/sample1/locations/sample2/memberships/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() - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) -def test_membership_path(): - project = "squid" - location = "clam" - membership = "whelk" - expected = ( - "projects/{project}/locations/{location}/memberships/{membership}".format( - project=project, - location=location, - membership=membership, - ) - ) - actual = GkeHubMembershipServiceClient.membership_path( - project, location, membership - ) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_parse_membership_path(): - expected = { - "project": "octopus", - "location": "oyster", - "membership": "nudibranch", - } - path = GkeHubMembershipServiceClient.membership_path(**expected) +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_membership_path(path) - assert expected == actual + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = GkeHubMembershipServiceClient.common_billing_account_path(billing_account) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = GkeHubMembershipServiceClient.common_billing_account_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_common_billing_account_path(path) - assert expected == actual + response = client.cancel_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = GkeHubMembershipServiceClient.common_folder_path(folder) - assert expected == actual +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = GkeHubMembershipServiceClient.common_folder_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_common_folder_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = GkeHubMembershipServiceClient.common_organization_path(organization) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = GkeHubMembershipServiceClient.common_organization_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_common_organization_path(path) - assert expected == actual + response = client.delete_operation(request) + # Establish that the response is the type that we expect. + assert response is None -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format( - project=project, - ) - actual = GkeHubMembershipServiceClient.common_project_path(project) - assert expected == actual +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = GkeHubMembershipServiceClient.common_project_path(**expected) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_common_project_path(path) - assert expected == actual + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - actual = GkeHubMembershipServiceClient.common_location_path(project, location) - assert expected == actual + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = GkeHubMembershipServiceClient.common_location_path(**expected) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Check that the path construction is reversible. - actual = GkeHubMembershipServiceClient.parse_common_location_path(path) - assert expected == actual + response = client.get_operation(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.GkeHubMembershipServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = GkeHubMembershipServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - with mock.patch.object( - transports.GkeHubMembershipServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = GkeHubMembershipServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = GkeHubMembershipServiceAsyncClient( + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = GkeHubMembershipServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) def test_delete_operation(transport: str = "grpc"): @@ -4716,6 +7805,7 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4733,6 +7823,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: