From e185233a978a99849790f7642086b1fe3ca6d626 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 16 Sep 2022 15:28:20 +0000 Subject: [PATCH] feat: Add support for REST transport (#152) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 474644226 Source-Link: https://github.com/googleapis/googleapis/commit/f90b329a7eb583a21a20796892b993e91e8ccf34 Source-Link: https://github.com/googleapis/googleapis-gen/commit/4ad8763bde676f92a3eb70753ae1cfed0e81387e Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNGFkODc2M2JkZTY3NmY5MmEzZWI3MDc1M2FlMWNmZWQwZTgxMzg3ZSJ9 PiperOrigin-RevId: 474571730 Source-Link: https://github.com/googleapis/googleapis/commit/5a9ee4d5deca8e3da550b0419ed336e22521fc8e Source-Link: https://github.com/googleapis/googleapis-gen/commit/ceafe521f137680fdee2f9ca9e1947cdd825070d Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiY2VhZmU1MjFmMTM3NjgwZmRlZTJmOWNhOWUxOTQ3Y2RkODI1MDcwZCJ9 fix(deps): require google-api-core>=1.33.1,>=2.8.0 fix(deps): require protobuf >= 3.20.1 --- .../gapic_metadata.json | 20 + .../services/private_catalog/client.py | 5 + .../private_catalog/transports/__init__.py | 4 + .../private_catalog/transports/rest.py | 615 +++++++++++ ..._catalog_search_catalogs_sync_92c68945.py} | 4 +- ...e_catalog_search_catalogs_sync_f4c0c8c0.py | 53 + ..._catalog_search_products_sync_91f2d094.py} | 4 +- ...e_catalog_search_products_sync_c80cb678.py | 53 + ..._catalog_search_versions_sync_9f509ae3.py} | 4 +- ...e_catalog_search_versions_sync_ae777daf.py | 54 + ...ippet_metadata_privatecatalog_v1beta1.json | 240 ++++- .../google-cloud-private-catalog/setup.py | 4 +- .../testing/constraints-3.7.txt | 4 +- .../test_private_catalog.py | 959 +++++++++++++++++- 14 files changed, 2003 insertions(+), 20 deletions(-) create mode 100644 packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py rename packages/google-cloud-private-catalog/samples/generated_samples/{cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py => cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py} (97%) create mode 100644 packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py rename packages/google-cloud-private-catalog/samples/generated_samples/{cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py => cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py} (97%) create mode 100644 packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py rename packages/google-cloud-private-catalog/samples/generated_samples/{cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py => cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py} (97%) create mode 100644 packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_metadata.json b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_metadata.json index ea77230d0dfb..b966bcfefef9 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_metadata.json @@ -46,6 +46,26 @@ ] } } + }, + "rest": { + "libraryClient": "PrivateCatalogClient", + "rpcs": { + "SearchCatalogs": { + "methods": [ + "search_catalogs" + ] + }, + "SearchProducts": { + "methods": [ + "search_products" + ] + }, + "SearchVersions": { + "methods": [ + "search_versions" + ] + } + } } } } diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/client.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/client.py index 148a55410393..442e2399295f 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/client.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/client.py @@ -40,6 +40,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, PrivateCatalogTransport from .transports.grpc import PrivateCatalogGrpcTransport from .transports.grpc_asyncio import PrivateCatalogGrpcAsyncIOTransport +from .transports.rest import PrivateCatalogRestTransport class PrivateCatalogClientMeta(type): @@ -55,6 +56,7 @@ class PrivateCatalogClientMeta(type): ) # type: Dict[str, Type[PrivateCatalogTransport]] _transport_registry["grpc"] = PrivateCatalogGrpcTransport _transport_registry["grpc_asyncio"] = PrivateCatalogGrpcAsyncIOTransport + _transport_registry["rest"] = PrivateCatalogRestTransport def get_transport_class( cls, @@ -400,6 +402,9 @@ def __init__( transport (Union[str, PrivateCatalogTransport]): The transport to use. If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/__init__.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/__init__.py index 2a0521c4b841..ce70e80fe38f 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/__init__.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/__init__.py @@ -19,14 +19,18 @@ from .base import PrivateCatalogTransport from .grpc import PrivateCatalogGrpcTransport from .grpc_asyncio import PrivateCatalogGrpcAsyncIOTransport +from .rest import PrivateCatalogRestInterceptor, PrivateCatalogRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[PrivateCatalogTransport]] _transport_registry["grpc"] = PrivateCatalogGrpcTransport _transport_registry["grpc_asyncio"] = PrivateCatalogGrpcAsyncIOTransport +_transport_registry["rest"] = PrivateCatalogRestTransport __all__ = ( "PrivateCatalogTransport", "PrivateCatalogGrpcTransport", "PrivateCatalogGrpcAsyncIOTransport", + "PrivateCatalogRestTransport", + "PrivateCatalogRestInterceptor", ) diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py new file mode 100644 index 000000000000..dd4380ff0299 --- /dev/null +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py @@ -0,0 +1,615 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.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.cloud.privatecatalog_v1beta1.types import private_catalog + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import PrivateCatalogTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class PrivateCatalogRestInterceptor: + """Interceptor for PrivateCatalog. + + 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 PrivateCatalogRestTransport. + + .. code-block:: python + class MyCustomPrivateCatalogInterceptor(PrivateCatalogRestInterceptor): + def pre_search_catalogs(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_catalogs(response): + logging.log(f"Received response: {response}") + + def pre_search_products(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_products(response): + logging.log(f"Received response: {response}") + + def pre_search_versions(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_versions(response): + logging.log(f"Received response: {response}") + + transport = PrivateCatalogRestTransport(interceptor=MyCustomPrivateCatalogInterceptor()) + client = PrivateCatalogClient(transport=transport) + + + """ + + def pre_search_catalogs( + self, + request: private_catalog.SearchCatalogsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[private_catalog.SearchCatalogsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_catalogs + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrivateCatalog server. + """ + return request, metadata + + def post_search_catalogs( + self, response: private_catalog.SearchCatalogsResponse + ) -> private_catalog.SearchCatalogsResponse: + """Post-rpc interceptor for search_catalogs + + Override in a subclass to manipulate the response + after it is returned by the PrivateCatalog server but before + it is returned to user code. + """ + return response + + def pre_search_products( + self, + request: private_catalog.SearchProductsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[private_catalog.SearchProductsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_products + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrivateCatalog server. + """ + return request, metadata + + def post_search_products( + self, response: private_catalog.SearchProductsResponse + ) -> private_catalog.SearchProductsResponse: + """Post-rpc interceptor for search_products + + Override in a subclass to manipulate the response + after it is returned by the PrivateCatalog server but before + it is returned to user code. + """ + return response + + def pre_search_versions( + self, + request: private_catalog.SearchVersionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[private_catalog.SearchVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the PrivateCatalog server. + """ + return request, metadata + + def post_search_versions( + self, response: private_catalog.SearchVersionsResponse + ) -> private_catalog.SearchVersionsResponse: + """Post-rpc interceptor for search_versions + + Override in a subclass to manipulate the response + after it is returned by the PrivateCatalog server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PrivateCatalogRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PrivateCatalogRestInterceptor + + +class PrivateCatalogRestTransport(PrivateCatalogTransport): + """REST backend transport for PrivateCatalog. + + ``PrivateCatalog`` allows catalog consumers to retrieve ``Catalog``, + ``Product`` and ``Version`` resources under a target resource + context. + + ``Catalog`` is computed based on the [Association][]s linked to the + target resource and its ancestors. Each association's + [google.cloud.privatecatalogproducer.v1beta.Catalog][] is + transformed into a ``Catalog``. If multiple associations have the + same parent [google.cloud.privatecatalogproducer.v1beta.Catalog][], + they are de-duplicated into one ``Catalog``. Users must have + ``cloudprivatecatalog.catalogTargets.get`` IAM permission on the + resource context in order to access catalogs. ``Catalog`` contains + the resource name and a subset of data of the original + [google.cloud.privatecatalogproducer.v1beta.Catalog][]. + + ``Product`` is child resource of the catalog. A ``Product`` contains + the resource name and a subset of the data of the original + [google.cloud.privatecatalogproducer.v1beta.Product][]. + + ``Version`` is child resource of the product. A ``Version`` contains + the resource name and a subset of the data of the original + [google.cloud.privatecatalogproducer.v1beta.Version][]. + + 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 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "cloudprivatecatalog.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: 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[PrivateCatalogRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PrivateCatalogRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _SearchCatalogs(PrivateCatalogRestStub): + def __hash__(self): + return hash("SearchCatalogs") + + __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: private_catalog.SearchCatalogsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> private_catalog.SearchCatalogsResponse: + r"""Call the search catalogs method over HTTP. + + Args: + request (~.private_catalog.SearchCatalogsRequest): + The request object. Request message for + [PrivateCatalog.SearchCatalogs][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchCatalogs]. + + 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: + ~.private_catalog.SearchCatalogsResponse: + Response message for + [PrivateCatalog.SearchCatalogs][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchCatalogs]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/catalogs:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/catalogs:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/catalogs:search", + }, + ] + request, metadata = self._interceptor.pre_search_catalogs(request, metadata) + pb_request = private_catalog.SearchCatalogsRequest.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=False, + ) + ) + query_params.update(self._get_unset_required_fields(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, 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 = private_catalog.SearchCatalogsResponse() + pb_resp = private_catalog.SearchCatalogsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_catalogs(resp) + return resp + + class _SearchProducts(PrivateCatalogRestStub): + def __hash__(self): + return hash("SearchProducts") + + __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: private_catalog.SearchProductsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> private_catalog.SearchProductsResponse: + r"""Call the search products method over HTTP. + + Args: + request (~.private_catalog.SearchProductsRequest): + The request object. Request message for + [PrivateCatalog.SearchProducts][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchProducts]. + + 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: + ~.private_catalog.SearchProductsResponse: + Response message for + [PrivateCatalog.SearchProducts][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchProducts]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/products:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/products:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/products:search", + }, + ] + request, metadata = self._interceptor.pre_search_products(request, metadata) + pb_request = private_catalog.SearchProductsRequest.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=False, + ) + ) + query_params.update(self._get_unset_required_fields(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, 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 = private_catalog.SearchProductsResponse() + pb_resp = private_catalog.SearchProductsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_products(resp) + return resp + + class _SearchVersions(PrivateCatalogRestStub): + def __hash__(self): + return hash("SearchVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "query": "", + } + + @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: private_catalog.SearchVersionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> private_catalog.SearchVersionsResponse: + r"""Call the search versions method over HTTP. + + Args: + request (~.private_catalog.SearchVersionsRequest): + The request object. Request message for + [PrivateCatalog.SearchVersions][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchVersions]. + + 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: + ~.private_catalog.SearchVersionsResponse: + Response message for + [PrivateCatalog.SearchVersions][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchVersions]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/versions:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/versions:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/versions:search", + }, + ] + request, metadata = self._interceptor.pre_search_versions(request, metadata) + pb_request = private_catalog.SearchVersionsRequest.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=False, + ) + ) + query_params.update(self._get_unset_required_fields(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, 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 = private_catalog.SearchVersionsResponse() + pb_resp = private_catalog.SearchVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_versions(resp) + return resp + + @property + def search_catalogs( + self, + ) -> Callable[ + [private_catalog.SearchCatalogsRequest], private_catalog.SearchCatalogsResponse + ]: + # 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._SearchCatalogs(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_products( + self, + ) -> Callable[ + [private_catalog.SearchProductsRequest], private_catalog.SearchProductsResponse + ]: + # 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._SearchProducts(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_versions( + self, + ) -> Callable[ + [private_catalog.SearchVersionsRequest], private_catalog.SearchVersionsResponse + ]: + # 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._SearchVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PrivateCatalogRestTransport",) diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py similarity index 97% rename from packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py rename to packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py index 52a85a10d71c..18cc6934be61 100644 --- a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-private-catalog -# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync] +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync_92c68945] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -50,4 +50,4 @@ def sample_search_catalogs(): for response in page_result: print(response) -# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync] +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync_92c68945] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py new file mode 100644 index 000000000000..70ac7beebdbc --- /dev/null +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-private-catalog + + +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync_f4c0c8c0] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import privatecatalog_v1beta1 + + +def sample_search_catalogs(): + # Create a client + client = privatecatalog_v1beta1.PrivateCatalogClient() + + # Initialize request argument(s) + request = privatecatalog_v1beta1.SearchCatalogsRequest( + resource="resource_value", + ) + + # Make the request + page_result = client.search_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync_f4c0c8c0] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py similarity index 97% rename from packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py rename to packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py index b62294d5865a..bbe2258fc9ba 100644 --- a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-private-catalog -# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync] +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync_91f2d094] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -50,4 +50,4 @@ def sample_search_products(): for response in page_result: print(response) -# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync] +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync_91f2d094] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py new file mode 100644 index 000000000000..d58664fcf3b0 --- /dev/null +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchProducts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-private-catalog + + +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync_c80cb678] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import privatecatalog_v1beta1 + + +def sample_search_products(): + # Create a client + client = privatecatalog_v1beta1.PrivateCatalogClient() + + # Initialize request argument(s) + request = privatecatalog_v1beta1.SearchProductsRequest( + resource="resource_value", + ) + + # Make the request + page_result = client.search_products(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync_c80cb678] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py similarity index 97% rename from packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py rename to packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py index 5a3215dd4d66..887ee336f175 100644 --- a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-private-catalog -# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync] +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync_9f509ae3] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -51,4 +51,4 @@ def sample_search_versions(): for response in page_result: print(response) -# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync] +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync_9f509ae3] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py new file mode 100644 index 000000000000..90e829024a5d --- /dev/null +++ b/packages/google-cloud-private-catalog/samples/generated_samples/cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-private-catalog + + +# [START cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync_ae777daf] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import privatecatalog_v1beta1 + + +def sample_search_versions(): + # Create a client + client = privatecatalog_v1beta1.PrivateCatalogClient() + + # Initialize request argument(s) + request = privatecatalog_v1beta1.SearchVersionsRequest( + resource="resource_value", + query="query_value", + ) + + # Make the request + page_result = client.search_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync_ae777daf] diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_privatecatalog_v1beta1.json b/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_privatecatalog_v1beta1.json index 43fa5f0f3975..4be1a82b783a 100644 --- a/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_privatecatalog_v1beta1.json +++ b/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_privatecatalog_v1beta1.json @@ -125,7 +125,7 @@ "shortName": "search_catalogs" }, "description": "Sample for SearchCatalogs", - "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync", @@ -161,7 +161,83 @@ "type": "RESPONSE_HANDLING" } ], - "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync.py" + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_f4c0c8c0.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient", + "shortName": "PrivateCatalogClient" + }, + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient.search_catalogs", + "method": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchCatalogs", + "service": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog", + "shortName": "PrivateCatalog" + }, + "shortName": "SearchCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.privatecatalog_v1beta1.types.SearchCatalogsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.privatecatalog_v1beta1.services.private_catalog.pagers.SearchCatalogsPager", + "shortName": "search_catalogs" + }, + "description": "Sample for SearchCatalogs", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchCatalogs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_catalogs_sync_92c68945.py" }, { "canonical": true, @@ -278,7 +354,83 @@ "shortName": "search_products" }, "description": "Sample for SearchProducts", - "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_c80cb678.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient", + "shortName": "PrivateCatalogClient" + }, + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient.search_products", + "method": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchProducts", + "service": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog", + "shortName": "PrivateCatalog" + }, + "shortName": "SearchProducts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.privatecatalog_v1beta1.types.SearchProductsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.privatecatalog_v1beta1.services.private_catalog.pagers.SearchProductsPager", + "shortName": "search_products" + }, + "description": "Sample for SearchProducts", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchProducts_sync", @@ -314,7 +466,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync.py" + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_products_sync_91f2d094.py" }, { "canonical": true, @@ -431,7 +583,83 @@ "shortName": "search_versions" }, "description": "Sample for SearchVersions", - "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_ae777daf.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient", + "shortName": "PrivateCatalogClient" + }, + "fullName": "google.cloud.privatecatalog_v1beta1.PrivateCatalogClient.search_versions", + "method": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchVersions", + "service": { + "fullName": "google.cloud.privatecatalog.v1beta1.PrivateCatalog", + "shortName": "PrivateCatalog" + }, + "shortName": "SearchVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.privatecatalog_v1beta1.types.SearchVersionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.privatecatalog_v1beta1.services.private_catalog.pagers.SearchVersionsPager", + "shortName": "search_versions" + }, + "description": "Sample for SearchVersions", + "file": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "cloudprivatecatalog_v1beta1_generated_PrivateCatalog_SearchVersions_sync", @@ -467,7 +695,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync.py" + "title": "cloudprivatecatalog_v1beta1_generated_private_catalog_search_versions_sync_9f509ae3.py" } ] } diff --git a/packages/google-cloud-private-catalog/setup.py b/packages/google-cloud-private-catalog/setup.py index 4eaa0d663505..c87157beef34 100644 --- a/packages/google-cloud-private-catalog/setup.py +++ b/packages/google-cloud-private-catalog/setup.py @@ -23,9 +23,9 @@ version = "0.6.2" release_status = "Development Status :: 4 - Beta" dependencies = [ - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.33.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf >= 3.19.0, <5.0.0dev", + "protobuf >= 3.20.1, <5.0.0dev", ] package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/google-cloud-private-catalog/testing/constraints-3.7.txt b/packages/google-cloud-private-catalog/testing/constraints-3.7.txt index 810c7cb36c5f..12cb23a09318 100644 --- a/packages/google-cloud-private-catalog/testing/constraints-3.7.txt +++ b/packages/google-cloud-private-catalog/testing/constraints-3.7.txt @@ -4,6 +4,6 @@ # Pin the version to the lower bound. # e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", # Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.32.0 +google-api-core==1.33.1 proto-plus==1.22.0 -protobuf==3.19.0 +protobuf==3.20.1 diff --git a/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py b/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py index d2e1190798f9..dd23307fc7d6 100644 --- a/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py +++ b/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,11 +33,14 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.privatecatalog_v1beta1.services.private_catalog import ( PrivateCatalogAsyncClient, @@ -95,6 +100,7 @@ def test__get_default_mtls_endpoint(): [ (PrivateCatalogClient, "grpc"), (PrivateCatalogAsyncClient, "grpc_asyncio"), + (PrivateCatalogClient, "rest"), ], ) def test_private_catalog_client_from_service_account_info(client_class, transport_name): @@ -108,7 +114,11 @@ def test_private_catalog_client_from_service_account_info(client_class, transpor assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudprivatecatalog.googleapis.com:443") + assert client.transport._host == ( + "cloudprivatecatalog.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudprivatecatalog.googleapis.com" + ) @pytest.mark.parametrize( @@ -116,6 +126,7 @@ def test_private_catalog_client_from_service_account_info(client_class, transpor [ (transports.PrivateCatalogGrpcTransport, "grpc"), (transports.PrivateCatalogGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PrivateCatalogRestTransport, "rest"), ], ) def test_private_catalog_client_service_account_always_use_jwt( @@ -141,6 +152,7 @@ def test_private_catalog_client_service_account_always_use_jwt( [ (PrivateCatalogClient, "grpc"), (PrivateCatalogAsyncClient, "grpc_asyncio"), + (PrivateCatalogClient, "rest"), ], ) def test_private_catalog_client_from_service_account_file(client_class, transport_name): @@ -161,13 +173,18 @@ def test_private_catalog_client_from_service_account_file(client_class, transpor assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudprivatecatalog.googleapis.com:443") + assert client.transport._host == ( + "cloudprivatecatalog.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudprivatecatalog.googleapis.com" + ) def test_private_catalog_client_get_transport_class(): transport = PrivateCatalogClient.get_transport_class() available_transports = [ transports.PrivateCatalogGrpcTransport, + transports.PrivateCatalogRestTransport, ] assert transport in available_transports @@ -184,6 +201,7 @@ def test_private_catalog_client_get_transport_class(): transports.PrivateCatalogGrpcAsyncIOTransport, "grpc_asyncio", ), + (PrivateCatalogClient, transports.PrivateCatalogRestTransport, "rest"), ], ) @mock.patch.object( @@ -329,6 +347,8 @@ def test_private_catalog_client_client_options( "grpc_asyncio", "false", ), + (PrivateCatalogClient, transports.PrivateCatalogRestTransport, "rest", "true"), + (PrivateCatalogClient, transports.PrivateCatalogRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -528,6 +548,7 @@ def test_private_catalog_client_get_mtls_endpoint_and_cert_source(client_class): transports.PrivateCatalogGrpcAsyncIOTransport, "grpc_asyncio", ), + (PrivateCatalogClient, transports.PrivateCatalogRestTransport, "rest"), ], ) def test_private_catalog_client_client_options_scopes( @@ -568,6 +589,7 @@ def test_private_catalog_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (PrivateCatalogClient, transports.PrivateCatalogRestTransport, "rest", None), ], ) def test_private_catalog_client_client_options_credentials_file( @@ -1694,6 +1716,881 @@ async def test_search_versions_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + private_catalog.SearchCatalogsRequest, + dict, + ], +) +def test_search_catalogs_rest(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "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 = private_catalog.SearchCatalogsResponse( + 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 = private_catalog.SearchCatalogsResponse.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.search_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_search_catalogs_rest_required_fields( + request_type=private_catalog.SearchCatalogsRequest, +): + transport_class = transports.PrivateCatalogRestTransport + + request_init = {} + request_init["resource"] = "" + 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() + ).search_catalogs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_catalogs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "query", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = private_catalog.SearchCatalogsResponse() + # 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 = private_catalog.SearchCatalogsResponse.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.search_catalogs(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_catalogs_rest_unset_required_fields(): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_catalogs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set(("resource",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_catalogs_rest_interceptors(null_interceptor): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivateCatalogRestInterceptor(), + ) + client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_catalogs" + ) as post, mock.patch.object( + transports.PrivateCatalogRestInterceptor, "pre_search_catalogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = private_catalog.SearchCatalogsRequest.pb( + private_catalog.SearchCatalogsRequest() + ) + 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 = private_catalog.SearchCatalogsResponse.to_json( + private_catalog.SearchCatalogsResponse() + ) + + request = private_catalog.SearchCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = private_catalog.SearchCatalogsResponse() + + client.search_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_catalogs_rest_bad_request( + transport: str = "rest", request_type=private_catalog.SearchCatalogsRequest +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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.search_catalogs(request) + + +def test_search_catalogs_rest_pager(transport: str = "rest"): + client = PrivateCatalogClient( + 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 = ( + private_catalog.SearchCatalogsResponse( + catalogs=[ + private_catalog.Catalog(), + private_catalog.Catalog(), + private_catalog.Catalog(), + ], + next_page_token="abc", + ), + private_catalog.SearchCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + private_catalog.SearchCatalogsResponse( + catalogs=[ + private_catalog.Catalog(), + ], + next_page_token="ghi", + ), + private_catalog.SearchCatalogsResponse( + catalogs=[ + private_catalog.Catalog(), + private_catalog.Catalog(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + private_catalog.SearchCatalogsResponse.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 = {"resource": "projects/sample1"} + + pager = client.search_catalogs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, private_catalog.Catalog) for i in results) + + pages = list(client.search_catalogs(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", + [ + private_catalog.SearchProductsRequest, + dict, + ], +) +def test_search_products_rest(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "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 = private_catalog.SearchProductsResponse( + 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 = private_catalog.SearchProductsResponse.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.search_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProductsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_search_products_rest_required_fields( + request_type=private_catalog.SearchProductsRequest, +): + transport_class = transports.PrivateCatalogRestTransport + + request_init = {} + request_init["resource"] = "" + 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() + ).search_products._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_products._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "query", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = private_catalog.SearchProductsResponse() + # 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 = private_catalog.SearchProductsResponse.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.search_products(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_products_rest_unset_required_fields(): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_products._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set(("resource",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_products_rest_interceptors(null_interceptor): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivateCatalogRestInterceptor(), + ) + client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_products" + ) as post, mock.patch.object( + transports.PrivateCatalogRestInterceptor, "pre_search_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = private_catalog.SearchProductsRequest.pb( + private_catalog.SearchProductsRequest() + ) + 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 = private_catalog.SearchProductsResponse.to_json( + private_catalog.SearchProductsResponse() + ) + + request = private_catalog.SearchProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = private_catalog.SearchProductsResponse() + + client.search_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_products_rest_bad_request( + transport: str = "rest", request_type=private_catalog.SearchProductsRequest +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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.search_products(request) + + +def test_search_products_rest_pager(transport: str = "rest"): + client = PrivateCatalogClient( + 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 = ( + private_catalog.SearchProductsResponse( + products=[ + private_catalog.Product(), + private_catalog.Product(), + private_catalog.Product(), + ], + next_page_token="abc", + ), + private_catalog.SearchProductsResponse( + products=[], + next_page_token="def", + ), + private_catalog.SearchProductsResponse( + products=[ + private_catalog.Product(), + ], + next_page_token="ghi", + ), + private_catalog.SearchProductsResponse( + products=[ + private_catalog.Product(), + private_catalog.Product(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + private_catalog.SearchProductsResponse.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 = {"resource": "projects/sample1"} + + pager = client.search_products(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, private_catalog.Product) for i in results) + + pages = list(client.search_products(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", + [ + private_catalog.SearchVersionsRequest, + dict, + ], +) +def test_search_versions_rest(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "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 = private_catalog.SearchVersionsResponse( + 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 = private_catalog.SearchVersionsResponse.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.search_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_search_versions_rest_required_fields( + request_type=private_catalog.SearchVersionsRequest, +): + transport_class = transports.PrivateCatalogRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["query"] = "" + 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 "query" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] + + jsonified_request["resource"] = "resource_value" + jsonified_request["query"] = "query_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "query", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = private_catalog.SearchVersionsResponse() + # 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 = private_catalog.SearchVersionsResponse.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.search_versions(request) + + expected_params = [ + ( + "query", + "", + ), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_versions_rest_unset_required_fields(): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set( + ( + "resource", + "query", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_versions_rest_interceptors(null_interceptor): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivateCatalogRestInterceptor(), + ) + client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_versions" + ) as post, mock.patch.object( + transports.PrivateCatalogRestInterceptor, "pre_search_versions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = private_catalog.SearchVersionsRequest.pb( + private_catalog.SearchVersionsRequest() + ) + 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 = private_catalog.SearchVersionsResponse.to_json( + private_catalog.SearchVersionsResponse() + ) + + request = private_catalog.SearchVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = private_catalog.SearchVersionsResponse() + + client.search_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_versions_rest_bad_request( + transport: str = "rest", request_type=private_catalog.SearchVersionsRequest +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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.search_versions(request) + + +def test_search_versions_rest_pager(transport: str = "rest"): + client = PrivateCatalogClient( + 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 = ( + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + private_catalog.Version(), + private_catalog.Version(), + ], + next_page_token="abc", + ), + private_catalog.SearchVersionsResponse( + versions=[], + next_page_token="def", + ), + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + ], + next_page_token="ghi", + ), + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + private_catalog.Version(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + private_catalog.SearchVersionsResponse.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 = {"resource": "projects/sample1"} + + pager = client.search_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, private_catalog.Version) for i in results) + + pages = list(client.search_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PrivateCatalogGrpcTransport( @@ -1775,6 +2672,7 @@ def test_transport_get_channel(): [ transports.PrivateCatalogGrpcTransport, transports.PrivateCatalogGrpcAsyncIOTransport, + transports.PrivateCatalogRestTransport, ], ) def test_transport_adc(transport_class): @@ -1789,6 +2687,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1920,6 +2819,7 @@ def test_private_catalog_transport_auth_adc(transport_class): [ transports.PrivateCatalogGrpcTransport, transports.PrivateCatalogGrpcAsyncIOTransport, + transports.PrivateCatalogRestTransport, ], ) def test_private_catalog_transport_auth_gdch_credentials(transport_class): @@ -2017,11 +2917,23 @@ def test_private_catalog_grpc_transport_client_cert_source_for_mtls(transport_cl ) +def test_private_catalog_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.PrivateCatalogRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_private_catalog_host_no_port(transport_name): @@ -2032,7 +2944,11 @@ def test_private_catalog_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudprivatecatalog.googleapis.com:443") + assert client.transport._host == ( + "cloudprivatecatalog.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudprivatecatalog.googleapis.com" + ) @pytest.mark.parametrize( @@ -2040,6 +2956,7 @@ def test_private_catalog_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_private_catalog_host_with_port(transport_name): @@ -2050,7 +2967,39 @@ def test_private_catalog_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudprivatecatalog.googleapis.com:8000") + assert client.transport._host == ( + "cloudprivatecatalog.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudprivatecatalog.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_private_catalog_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PrivateCatalogClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PrivateCatalogClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search_catalogs._session + session2 = client2.transport.search_catalogs._session + assert session1 != session2 + session1 = client1.transport.search_products._session + session2 = client2.transport.search_products._session + assert session1 != session2 + session1 = client1.transport.search_versions._session + session2 = client2.transport.search_versions._session + assert session1 != session2 def test_private_catalog_grpc_transport_channel(): @@ -2387,6 +3336,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2404,6 +3354,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: