From 0ccecb079d3702026d14ef577fda27030f19f3aa Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 13 Sep 2022 11:51:35 -0400 Subject: [PATCH] feat: Enable REST transport support (#45) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: integrate gapic-generator-python-1.4.1 and enable more py_test targets PiperOrigin-RevId: 473833416 Source-Link: https://github.com/googleapis/googleapis/commit/565a5508869557a3228b871101e4e4ebd8f93d11 Source-Link: https://github.com/googleapis/googleapis-gen/commit/1ee1a06c6de3ca8b843572c1fde0548f84236989 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMWVlMWEwNmM2ZGUzY2E4Yjg0MzU3MmMxZmRlMDU0OGY4NDIzNjk4OSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix(deps): require google-api-core>=1.33,>=2.8.0 * fix(deps): require protobuf >= 3.20.1 * remove transitive dependency Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- google/cloud/run_v2/gapic_metadata.json | 65 + .../cloud/run_v2/services/revisions/client.py | 5 + .../services/revisions/transports/__init__.py | 5 + .../services/revisions/transports/rest.py | 614 ++++ .../cloud/run_v2/services/services/client.py | 5 + .../services/services/transports/__init__.py | 5 + .../services/services/transports/rest.py | 1415 ++++++++ ...revisions_delete_revision_sync_2da46bc2.py | 56 + ...revisions_delete_revision_sync_d74b55e0.py | 56 + ...ed_revisions_get_revision_sync_115a25ad.py | 52 + ...ed_revisions_get_revision_sync_e5e5b0ac.py | 52 + ..._revisions_list_revisions_sync_1d0f1802.py | 53 + ..._revisions_list_revisions_sync_2312de2e.py | 53 + ...d_services_create_service_sync_3c405c33.py | 57 + ...d_services_create_service_sync_8031b824.py | 57 + ...d_services_delete_service_sync_91d4ca21.py | 56 + ...d_services_delete_service_sync_9c99d0a2.py | 56 + ...d_services_get_iam_policy_sync_449f2eb3.py | 53 + ...d_services_get_iam_policy_sync_9f45c2a7.py | 53 + ...ated_services_get_service_sync_18284d02.py | 52 + ...ated_services_get_service_sync_1c3ef02e.py | 52 + ...ed_services_list_services_sync_7dbaf490.py | 53 + ...ed_services_list_services_sync_c5743712.py | 53 + ...d_services_set_iam_policy_sync_b88666d6.py | 53 + ...d_services_set_iam_policy_sync_c710ebbc.py | 53 + ...ices_test_iam_permissions_sync_048b00bc.py | 54 + ...ices_test_iam_permissions_sync_7c7fb79b.py | 54 + ...d_services_update_service_sync_2652a462.py | 55 + ...d_services_update_service_sync_9076a854.py | 55 + .../snippet_metadata_run_v2.json | 1056 +++++- setup.py | 5 +- testing/constraints-3.7.txt | 5 +- tests/unit/gapic/run_v2/test_revisions.py | 1018 +++++- tests/unit/gapic/run_v2/test_services.py | 2861 ++++++++++++++++- 34 files changed, 8053 insertions(+), 194 deletions(-) create mode 100644 google/cloud/run_v2/services/revisions/transports/rest.py create mode 100644 google/cloud/run_v2/services/services/transports/rest.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_2da46bc2.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_d74b55e0.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_get_revision_sync_115a25ad.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_1d0f1802.py create mode 100644 samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_2312de2e.py create mode 100644 samples/generated_samples/run_v2_generated_services_create_service_sync_3c405c33.py create mode 100644 samples/generated_samples/run_v2_generated_services_create_service_sync_8031b824.py create mode 100644 samples/generated_samples/run_v2_generated_services_delete_service_sync_91d4ca21.py create mode 100644 samples/generated_samples/run_v2_generated_services_delete_service_sync_9c99d0a2.py create mode 100644 samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_449f2eb3.py create mode 100644 samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_9f45c2a7.py create mode 100644 samples/generated_samples/run_v2_generated_services_get_service_sync_18284d02.py create mode 100644 samples/generated_samples/run_v2_generated_services_get_service_sync_1c3ef02e.py create mode 100644 samples/generated_samples/run_v2_generated_services_list_services_sync_7dbaf490.py create mode 100644 samples/generated_samples/run_v2_generated_services_list_services_sync_c5743712.py create mode 100644 samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_b88666d6.py create mode 100644 samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_c710ebbc.py create mode 100644 samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_048b00bc.py create mode 100644 samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.py create mode 100644 samples/generated_samples/run_v2_generated_services_update_service_sync_2652a462.py create mode 100644 samples/generated_samples/run_v2_generated_services_update_service_sync_9076a854.py diff --git a/google/cloud/run_v2/gapic_metadata.json b/google/cloud/run_v2/gapic_metadata.json index 995df8c..e8920ee 100644 --- a/google/cloud/run_v2/gapic_metadata.json +++ b/google/cloud/run_v2/gapic_metadata.json @@ -46,6 +46,26 @@ ] } } + }, + "rest": { + "libraryClient": "RevisionsClient", + "rpcs": { + "DeleteRevision": { + "methods": [ + "delete_revision" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + } + } } } }, @@ -140,6 +160,51 @@ ] } } + }, + "rest": { + "libraryClient": "ServicesClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } } } } diff --git a/google/cloud/run_v2/services/revisions/client.py b/google/cloud/run_v2/services/revisions/client.py index 6668526..2ed4c32 100644 --- a/google/cloud/run_v2/services/revisions/client.py +++ b/google/cloud/run_v2/services/revisions/client.py @@ -47,6 +47,7 @@ from .transports.base import RevisionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RevisionsGrpcTransport from .transports.grpc_asyncio import RevisionsGrpcAsyncIOTransport +from .transports.rest import RevisionsRestTransport class RevisionsClientMeta(type): @@ -60,6 +61,7 @@ class RevisionsClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[RevisionsTransport]] _transport_registry["grpc"] = RevisionsGrpcTransport _transport_registry["grpc_asyncio"] = RevisionsGrpcAsyncIOTransport + _transport_registry["rest"] = RevisionsRestTransport def get_transport_class( cls, @@ -462,6 +464,9 @@ def __init__( transport (Union[str, RevisionsTransport]): 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/google/cloud/run_v2/services/revisions/transports/__init__.py b/google/cloud/run_v2/services/revisions/transports/__init__.py index ff3df68..a67304d 100644 --- a/google/cloud/run_v2/services/revisions/transports/__init__.py +++ b/google/cloud/run_v2/services/revisions/transports/__init__.py @@ -19,15 +19,20 @@ from .base import RevisionsTransport from .grpc import RevisionsGrpcTransport from .grpc_asyncio import RevisionsGrpcAsyncIOTransport +from .rest import RevisionsRestTransport +from .rest import RevisionsRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[RevisionsTransport]] _transport_registry["grpc"] = RevisionsGrpcTransport _transport_registry["grpc_asyncio"] = RevisionsGrpcAsyncIOTransport +_transport_registry["rest"] = RevisionsRestTransport __all__ = ( "RevisionsTransport", "RevisionsGrpcTransport", "RevisionsGrpcAsyncIOTransport", + "RevisionsRestTransport", + "RevisionsRestInterceptor", ) diff --git a/google/cloud/run_v2/services/revisions/transports/rest.py b/google/cloud/run_v2/services/revisions/transports/rest.py new file mode 100644 index 0000000..6472f72 --- /dev/null +++ b/google/cloud/run_v2/services/revisions/transports/rest.py @@ -0,0 +1,614 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.run_v2.types import revision +from google.longrunning import operations_pb2 # type: ignore + +from .base import RevisionsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RevisionsRestInterceptor: + """Interceptor for Revisions. + + 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 RevisionsRestTransport. + + .. code-block:: python + class MyCustomRevisionsInterceptor(RevisionsRestInterceptor): + def pre_delete_revision(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_revision(response): + logging.log(f"Received response: {response}") + + def pre_get_revision(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_revision(response): + logging.log(f"Received response: {response}") + + def pre_list_revisions(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_revisions(response): + logging.log(f"Received response: {response}") + + transport = RevisionsRestTransport(interceptor=MyCustomRevisionsInterceptor()) + client = RevisionsClient(transport=transport) + + + """ + + def pre_delete_revision( + self, + request: revision.DeleteRevisionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[revision.DeleteRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Revisions server. + """ + return request, metadata + + def post_delete_revision( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_revision + + Override in a subclass to manipulate the response + after it is returned by the Revisions server but before + it is returned to user code. + """ + return response + + def pre_get_revision( + self, request: revision.GetRevisionRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[revision.GetRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Revisions server. + """ + return request, metadata + + def post_get_revision(self, response: revision.Revision) -> revision.Revision: + """Post-rpc interceptor for get_revision + + Override in a subclass to manipulate the response + after it is returned by the Revisions server but before + it is returned to user code. + """ + return response + + def pre_list_revisions( + self, + request: revision.ListRevisionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[revision.ListRevisionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Revisions server. + """ + return request, metadata + + def post_list_revisions( + self, response: revision.ListRevisionsResponse + ) -> revision.ListRevisionsResponse: + """Post-rpc interceptor for list_revisions + + Override in a subclass to manipulate the response + after it is returned by the Revisions server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RevisionsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RevisionsRestInterceptor + + +class RevisionsRestTransport(RevisionsTransport): + """REST backend transport for Revisions. + + Cloud Run Revision Control Plane API. + + 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 = "run.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[RevisionsRestInterceptor] = 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 + ) + 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 RevisionsRestInterceptor() + 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.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{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, + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _DeleteRevision(RevisionsRestStub): + def __hash__(self): + return hash("DeleteRevision") + + __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: revision.DeleteRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete revision method over HTTP. + + Args: + request (~.revision.DeleteRevisionRequest): + The request object. Request message for deleting a + retired Revision. Revision lifecycle is + usually managed by making changes to the + parent Service. Only retired revisions + can be deleted with this API. + + 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": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_revision(request, metadata) + pb_request = revision.DeleteRevisionRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_revision(resp) + return resp + + class _GetRevision(RevisionsRestStub): + def __hash__(self): + return hash("GetRevision") + + __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: revision.GetRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> revision.Revision: + r"""Call the get revision method over HTTP. + + Args: + request (~.revision.GetRevisionRequest): + The request object. Request message for obtaining a + Revision by its full name. + + 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: + ~.revision.Revision: + A Revision is an immutable snapshot + of code and configuration. A Revision + references a container image. Revisions + are only created by updates to its + parent Service. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", + }, + ] + request, metadata = self._interceptor.pre_get_revision(request, metadata) + pb_request = revision.GetRevisionRequest.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 = revision.Revision() + pb_resp = revision.Revision.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_revision(resp) + return resp + + class _ListRevisions(RevisionsRestStub): + def __hash__(self): + return hash("ListRevisions") + + __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: revision.ListRevisionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> revision.ListRevisionsResponse: + r"""Call the list revisions method over HTTP. + + Args: + request (~.revision.ListRevisionsRequest): + The request object. Request message for retrieving a list + of Revisions. + + 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: + ~.revision.ListRevisionsResponse: + Response message containing a list of + Revisions. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/services/*}/revisions", + }, + ] + request, metadata = self._interceptor.pre_list_revisions(request, metadata) + pb_request = revision.ListRevisionsRequest.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 = revision.ListRevisionsResponse() + pb_resp = revision.ListRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_revisions(resp) + return resp + + @property + def delete_revision( + self, + ) -> Callable[[revision.DeleteRevisionRequest], 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._DeleteRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_revision( + self, + ) -> Callable[[revision.GetRevisionRequest], revision.Revision]: + # 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._GetRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_revisions( + self, + ) -> Callable[[revision.ListRevisionsRequest], revision.ListRevisionsResponse]: + # 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._ListRevisions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RevisionsRestTransport",) diff --git a/google/cloud/run_v2/services/services/client.py b/google/cloud/run_v2/services/services/client.py index 4248686..0ad702c 100644 --- a/google/cloud/run_v2/services/services/client.py +++ b/google/cloud/run_v2/services/services/client.py @@ -50,6 +50,7 @@ from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ServicesGrpcTransport from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport +from .transports.rest import ServicesRestTransport class ServicesClientMeta(type): @@ -63,6 +64,7 @@ class ServicesClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] _transport_registry["grpc"] = ServicesGrpcTransport _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport + _transport_registry["rest"] = ServicesRestTransport def get_transport_class( cls, @@ -465,6 +467,9 @@ def __init__( transport (Union[str, ServicesTransport]): 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/google/cloud/run_v2/services/services/transports/__init__.py b/google/cloud/run_v2/services/services/transports/__init__.py index 7597c5d..9c2d606 100644 --- a/google/cloud/run_v2/services/services/transports/__init__.py +++ b/google/cloud/run_v2/services/services/transports/__init__.py @@ -19,15 +19,20 @@ from .base import ServicesTransport from .grpc import ServicesGrpcTransport from .grpc_asyncio import ServicesGrpcAsyncIOTransport +from .rest import ServicesRestTransport +from .rest import ServicesRestInterceptor # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] _transport_registry["grpc"] = ServicesGrpcTransport _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport +_transport_registry["rest"] = ServicesRestTransport __all__ = ( "ServicesTransport", "ServicesGrpcTransport", "ServicesGrpcAsyncIOTransport", + "ServicesRestTransport", + "ServicesRestInterceptor", ) diff --git a/google/cloud/run_v2/services/services/transports/rest.py b/google/cloud/run_v2/services/services/transports/rest.py new file mode 100644 index 0000000..1eb89e6 --- /dev/null +++ b/google/cloud/run_v2/services/services/transports/rest.py @@ -0,0 +1,1415 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service +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 # type: ignore + +from .base import ServicesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ServicesRestInterceptor: + """Interceptor for Services. + + 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 ServicesRestTransport. + + .. code-block:: python + class MyCustomServicesInterceptor(ServicesRestInterceptor): + def pre_create_service(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_service(response): + logging.log(f"Received response: {response}") + + def pre_delete_service(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_service(response): + logging.log(f"Received response: {response}") + + def pre_get_iam_policy(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(response): + logging.log(f"Received response: {response}") + + def pre_get_service(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_service(response): + logging.log(f"Received response: {response}") + + def pre_list_services(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_services(response): + logging.log(f"Received response: {response}") + + def pre_set_iam_policy(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(response): + logging.log(f"Received response: {response}") + + def pre_test_iam_permissions(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(response): + logging.log(f"Received response: {response}") + + def pre_update_service(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_service(response): + logging.log(f"Received response: {response}") + + transport = ServicesRestTransport(interceptor=MyCustomServicesInterceptor()) + client = ServicesClient(transport=transport) + + + """ + + def pre_create_service( + self, + request: gcr_service.CreateServiceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcr_service.CreateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_create_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_service + + Override in a subclass to manipulate the response + after it is returned by the Services server but before + it is returned to user code. + """ + return response + + def pre_delete_service( + self, request: service.DeleteServiceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.DeleteServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_delete_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_service + + Override in a subclass to manipulate the response + after it is returned by the Services 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]], + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Services server but before + it is returned to user code. + """ + return response + + def pre_get_service( + self, request: service.GetServiceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_get_service(self, response: service.Service) -> service.Service: + """Post-rpc interceptor for get_service + + Override in a subclass to manipulate the response + after it is returned by the Services server but before + it is returned to user code. + """ + return response + + def pre_list_services( + self, request: service.ListServicesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListServicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_list_services( + self, response: service.ListServicesResponse + ) -> service.ListServicesResponse: + """Post-rpc interceptor for list_services + + Override in a subclass to manipulate the response + after it is returned by the Services 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]], + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Services 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]], + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> 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 Services server but before + it is returned to user code. + """ + return response + + def pre_update_service( + self, + request: gcr_service.UpdateServiceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcr_service.UpdateServiceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the Services server. + """ + return request, metadata + + def post_update_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_service + + Override in a subclass to manipulate the response + after it is returned by the Services server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ServicesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ServicesRestInterceptor + + +class ServicesRestTransport(ServicesTransport): + """REST backend transport for Services. + + Cloud Run Service Control Plane API + + 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 = "run.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[ServicesRestInterceptor] = 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 + ) + 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 ServicesRestInterceptor() + 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.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{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, + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateService(ServicesRestStub): + def __hash__(self): + return hash("CreateService") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "serviceId": "", + } + + @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: gcr_service.CreateServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create service method over HTTP. + + Args: + request (~.gcr_service.CreateServiceRequest): + The request object. Request message for creating a + Service. + + 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": "/v2/{parent=projects/*/locations/*}/services", + "body": "service", + }, + ] + request, metadata = self._interceptor.pre_create_service(request, metadata) + pb_request = gcr_service.CreateServiceRequest.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=False, + ) + 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), + 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_service(resp) + return resp + + class _DeleteService(ServicesRestStub): + def __hash__(self): + return hash("DeleteService") + + __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.DeleteServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete service method over HTTP. + + Args: + request (~.service.DeleteServiceRequest): + The request object. Request message to delete a Service + by its full name. + + 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": "/v2/{name=projects/*/locations/*/services/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_service(request, metadata) + pb_request = service.DeleteServiceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service(resp) + return resp + + class _GetIamPolicy(ServicesRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __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: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: 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. Request message 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:getIamPolicy", + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = 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 = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetService(ServicesRestStub): + def __hash__(self): + return hash("GetService") + + __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.GetServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Call the get service method over HTTP. + + Args: + request (~.service.GetServiceRequest): + The request object. Request message for obtaining a + Service by its full name. + + 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.Service: + Service acts as a top-level container + that manages a set of configurations and + revision templates which implement a + network service. Service exists to + provide a singular abstraction which can + be access controlled, reasoned about, + and which encapsulates software + lifecycle decisions such as rollout + policy and team resource ownership. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/services/*}", + }, + ] + request, metadata = self._interceptor.pre_get_service(request, metadata) + pb_request = service.GetServiceRequest.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 = service.Service() + pb_resp = service.Service.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service(resp) + return resp + + class _ListServices(ServicesRestStub): + def __hash__(self): + return hash("ListServices") + + __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.ListServicesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.service.ListServicesRequest): + The request object. Request message for retrieving a list + of Services. + + 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.ListServicesResponse: + Response message containing a list of + Services. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/services", + }, + ] + request, metadata = self._interceptor.pre_list_services(request, metadata) + pb_request = service.ListServicesRequest.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 = service.ListServicesResponse() + pb_resp = service.ListServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + return resp + + class _SetIamPolicy(ServicesRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __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: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: 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. Request message 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:setIamPolicy", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = 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=False, + ) + 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), + 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 = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(ServicesRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __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: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: 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. Request message 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 message for ``TestIamPermissions`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:testIamPermissions", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + pb_request = 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=False, + ) + 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), + 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 = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateService(ServicesRestStub): + def __hash__(self): + return hash("UpdateService") + + __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: gcr_service.UpdateServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update service method over HTTP. + + Args: + request (~.gcr_service.UpdateServiceRequest): + The request object. Request message for updating a + service. + + 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": "/v2/{service.name=projects/*/locations/*/services/*}", + "body": "service", + }, + ] + request, metadata = self._interceptor.pre_update_service(request, metadata) + pb_request = gcr_service.UpdateServiceRequest.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=False, + ) + 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), + 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_service(resp) + return resp + + @property + def create_service( + self, + ) -> Callable[[gcr_service.CreateServiceRequest], 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._CreateService(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_service( + self, + ) -> Callable[[service.DeleteServiceRequest], 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._DeleteService(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_service(self) -> Callable[[service.GetServiceRequest], service.Service]: + # 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._GetService(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_services( + self, + ) -> Callable[[service.ListServicesRequest], service.ListServicesResponse]: + # 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._ListServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + # 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._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + # 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._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_service( + self, + ) -> Callable[[gcr_service.UpdateServiceRequest], 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._UpdateService(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ServicesRestTransport",) diff --git a/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_2da46bc2.py b/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_2da46bc2.py new file mode 100644 index 0000000..058af22 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_2da46bc2.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteRevision +# 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-run + + +# [START run_v2_generated_Revisions_DeleteRevision_sync_2da46bc2] +# 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 run_v2 + + +def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_DeleteRevision_sync_2da46bc2] diff --git a/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_d74b55e0.py b/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_d74b55e0.py new file mode 100644 index 0000000..55cea76 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_delete_revision_sync_d74b55e0.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteRevision +# 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-run + + +# [START run_v2_generated_Revisions_DeleteRevision_sync_d74b55e0] +# 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 run_v2 + + +def sample_delete_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.DeleteRevisionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_revision(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_DeleteRevision_sync_d74b55e0] diff --git a/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_115a25ad.py b/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_115a25ad.py new file mode 100644 index 0000000..31661cc --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_115a25ad.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRevision +# 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-run + + +# [START run_v2_generated_Revisions_GetRevision_sync_115a25ad] +# 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 run_v2 + + +def sample_get_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_GetRevision_sync_115a25ad] diff --git a/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py b/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py new file mode 100644 index 0000000..5eac5cd --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRevision +# 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-run + + +# [START run_v2_generated_Revisions_GetRevision_sync_e5e5b0ac] +# 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 run_v2 + + +def sample_get_revision(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Revisions_GetRevision_sync_e5e5b0ac] diff --git a/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_1d0f1802.py b/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_1d0f1802.py new file mode 100644 index 0000000..85c3992 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_1d0f1802.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 ListRevisions +# 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-run + + +# [START run_v2_generated_Revisions_ListRevisions_sync_1d0f1802] +# 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 run_v2 + + +def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Revisions_ListRevisions_sync_1d0f1802] diff --git a/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_2312de2e.py b/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_2312de2e.py new file mode 100644 index 0000000..7695c69 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_revisions_list_revisions_sync_2312de2e.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 ListRevisions +# 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-run + + +# [START run_v2_generated_Revisions_ListRevisions_sync_2312de2e] +# 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 run_v2 + + +def sample_list_revisions(): + # Create a client + client = run_v2.RevisionsClient() + + # Initialize request argument(s) + request = run_v2.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Revisions_ListRevisions_sync_2312de2e] diff --git a/samples/generated_samples/run_v2_generated_services_create_service_sync_3c405c33.py b/samples/generated_samples/run_v2_generated_services_create_service_sync_3c405c33.py new file mode 100644 index 0000000..d998b0d --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_create_service_sync_3c405c33.py @@ -0,0 +1,57 @@ +# -*- 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 CreateService +# 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-run + + +# [START run_v2_generated_Services_CreateService_sync_3c405c33] +# 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 run_v2 + + +def sample_create_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_CreateService_sync_3c405c33] diff --git a/samples/generated_samples/run_v2_generated_services_create_service_sync_8031b824.py b/samples/generated_samples/run_v2_generated_services_create_service_sync_8031b824.py new file mode 100644 index 0000000..2ec8a39 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_create_service_sync_8031b824.py @@ -0,0 +1,57 @@ +# -*- 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 CreateService +# 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-run + + +# [START run_v2_generated_Services_CreateService_sync_8031b824] +# 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 run_v2 + + +def sample_create_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.CreateServiceRequest( + parent="parent_value", + service_id="service_id_value", + ) + + # Make the request + operation = client.create_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_CreateService_sync_8031b824] diff --git a/samples/generated_samples/run_v2_generated_services_delete_service_sync_91d4ca21.py b/samples/generated_samples/run_v2_generated_services_delete_service_sync_91d4ca21.py new file mode 100644 index 0000000..08b4776 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_delete_service_sync_91d4ca21.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteService +# 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-run + + +# [START run_v2_generated_Services_DeleteService_sync_91d4ca21] +# 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 run_v2 + + +def sample_delete_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_DeleteService_sync_91d4ca21] diff --git a/samples/generated_samples/run_v2_generated_services_delete_service_sync_9c99d0a2.py b/samples/generated_samples/run_v2_generated_services_delete_service_sync_9c99d0a2.py new file mode 100644 index 0000000..4ce2d70 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_delete_service_sync_9c99d0a2.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteService +# 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-run + + +# [START run_v2_generated_Services_DeleteService_sync_9c99d0a2] +# 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 run_v2 + + +def sample_delete_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.DeleteServiceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_DeleteService_sync_9c99d0a2] diff --git a/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_449f2eb3.py b/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_449f2eb3.py new file mode 100644 index 0000000..ae6c0cd --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_449f2eb3.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 GetIamPolicy +# 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-run + + +# [START run_v2_generated_Services_GetIamPolicy_sync_449f2eb3] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetIamPolicy_sync_449f2eb3] diff --git a/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_9f45c2a7.py b/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_9f45c2a7.py new file mode 100644 index 0000000..62a767f --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_get_iam_policy_sync_9f45c2a7.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 GetIamPolicy +# 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-run + + +# [START run_v2_generated_Services_GetIamPolicy_sync_9f45c2a7] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetIamPolicy_sync_9f45c2a7] diff --git a/samples/generated_samples/run_v2_generated_services_get_service_sync_18284d02.py b/samples/generated_samples/run_v2_generated_services_get_service_sync_18284d02.py new file mode 100644 index 0000000..6280f7f --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_get_service_sync_18284d02.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-run + + +# [START run_v2_generated_Services_GetService_sync_18284d02] +# 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 run_v2 + + +def sample_get_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetService_sync_18284d02] diff --git a/samples/generated_samples/run_v2_generated_services_get_service_sync_1c3ef02e.py b/samples/generated_samples/run_v2_generated_services_get_service_sync_1c3ef02e.py new file mode 100644 index 0000000..5c32f50 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_get_service_sync_1c3ef02e.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# 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-run + + +# [START run_v2_generated_Services_GetService_sync_1c3ef02e] +# 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 run_v2 + + +def sample_get_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.GetServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_GetService_sync_1c3ef02e] diff --git a/samples/generated_samples/run_v2_generated_services_list_services_sync_7dbaf490.py b/samples/generated_samples/run_v2_generated_services_list_services_sync_7dbaf490.py new file mode 100644 index 0000000..7d44aa7 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_list_services_sync_7dbaf490.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 ListServices +# 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-run + + +# [START run_v2_generated_Services_ListServices_sync_7dbaf490] +# 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 run_v2 + + +def sample_list_services(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Services_ListServices_sync_7dbaf490] diff --git a/samples/generated_samples/run_v2_generated_services_list_services_sync_c5743712.py b/samples/generated_samples/run_v2_generated_services_list_services_sync_c5743712.py new file mode 100644 index 0000000..b14c8b4 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_list_services_sync_c5743712.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 ListServices +# 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-run + + +# [START run_v2_generated_Services_ListServices_sync_c5743712] +# 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 run_v2 + + +def sample_list_services(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.ListServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END run_v2_generated_Services_ListServices_sync_c5743712] diff --git a/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_b88666d6.py b/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_b88666d6.py new file mode 100644 index 0000000..d3f53e2 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_b88666d6.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 SetIamPolicy +# 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-run + + +# [START run_v2_generated_Services_SetIamPolicy_sync_b88666d6] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_SetIamPolicy_sync_b88666d6] diff --git a/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_c710ebbc.py b/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_c710ebbc.py new file mode 100644 index 0000000..14641dc --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_set_iam_policy_sync_c710ebbc.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 SetIamPolicy +# 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-run + + +# [START run_v2_generated_Services_SetIamPolicy_sync_c710ebbc] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_SetIamPolicy_sync_c710ebbc] diff --git a/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_048b00bc.py b/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_048b00bc.py new file mode 100644 index 0000000..b53a243 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_048b00bc.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 TestIamPermissions +# 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-run + + +# [START run_v2_generated_Services_TestIamPermissions_sync_048b00bc] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_TestIamPermissions_sync_048b00bc] diff --git a/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.py b/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.py new file mode 100644 index 0000000..333f714 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.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 TestIamPermissions +# 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-run + + +# [START run_v2_generated_Services_TestIamPermissions_sync_7c7fb79b] +# 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 run_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END run_v2_generated_Services_TestIamPermissions_sync_7c7fb79b] diff --git a/samples/generated_samples/run_v2_generated_services_update_service_sync_2652a462.py b/samples/generated_samples/run_v2_generated_services_update_service_sync_2652a462.py new file mode 100644 index 0000000..549b76b --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_update_service_sync_2652a462.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateService +# 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-run + + +# [START run_v2_generated_Services_UpdateService_sync_2652a462] +# 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 run_v2 + + +def sample_update_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_UpdateService_sync_2652a462] diff --git a/samples/generated_samples/run_v2_generated_services_update_service_sync_9076a854.py b/samples/generated_samples/run_v2_generated_services_update_service_sync_9076a854.py new file mode 100644 index 0000000..37a8fe6 --- /dev/null +++ b/samples/generated_samples/run_v2_generated_services_update_service_sync_9076a854.py @@ -0,0 +1,55 @@ +# -*- 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 UpdateService +# 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-run + + +# [START run_v2_generated_Services_UpdateService_sync_9076a854] +# 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 run_v2 + + +def sample_update_service(): + # Create a client + client = run_v2.ServicesClient() + + # Initialize request argument(s) + request = run_v2.UpdateServiceRequest( + ) + + # Make the request + operation = client.update_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END run_v2_generated_Services_UpdateService_sync_9076a854] diff --git a/samples/generated_samples/snippet_metadata_run_v2.json b/samples/generated_samples/snippet_metadata_run_v2.json index fe7fed3..f9b04b1 100644 --- a/samples/generated_samples/snippet_metadata_run_v2.json +++ b/samples/generated_samples/snippet_metadata_run_v2.json @@ -133,7 +133,7 @@ "shortName": "delete_revision" }, "description": "Sample for DeleteRevision", - "file": "run_v2_generated_revisions_delete_revision_sync.py", + "file": "run_v2_generated_revisions_delete_revision_sync_2da46bc2.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Revisions_DeleteRevision_sync", @@ -169,7 +169,87 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_revisions_delete_revision_sync.py" + "title": "run_v2_generated_revisions_delete_revision_sync_2da46bc2.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.RevisionsClient", + "shortName": "RevisionsClient" + }, + "fullName": "google.cloud.run_v2.RevisionsClient.delete_revision", + "method": { + "fullName": "google.cloud.run.v2.Revisions.DeleteRevision", + "service": { + "fullName": "google.cloud.run.v2.Revisions", + "shortName": "Revisions" + }, + "shortName": "DeleteRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.DeleteRevisionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_revision" + }, + "description": "Sample for DeleteRevision", + "file": "run_v2_generated_revisions_delete_revision_sync_d74b55e0.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Revisions_DeleteRevision_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_revisions_delete_revision_sync_d74b55e0.py" }, { "canonical": true, @@ -294,7 +374,87 @@ "shortName": "get_revision" }, "description": "Sample for GetRevision", - "file": "run_v2_generated_revisions_get_revision_sync.py", + "file": "run_v2_generated_revisions_get_revision_sync_115a25ad.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Revisions_GetRevision_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_revisions_get_revision_sync_115a25ad.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.RevisionsClient", + "shortName": "RevisionsClient" + }, + "fullName": "google.cloud.run_v2.RevisionsClient.get_revision", + "method": { + "fullName": "google.cloud.run.v2.Revisions.GetRevision", + "service": { + "fullName": "google.cloud.run.v2.Revisions", + "shortName": "Revisions" + }, + "shortName": "GetRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.GetRevisionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.run_v2.types.Revision", + "shortName": "get_revision" + }, + "description": "Sample for GetRevision", + "file": "run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Revisions_GetRevision_sync", @@ -330,7 +490,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_revisions_get_revision_sync.py" + "title": "run_v2_generated_revisions_get_revision_sync_e5e5b0ac.py" }, { "canonical": true, @@ -455,7 +615,87 @@ "shortName": "list_revisions" }, "description": "Sample for ListRevisions", - "file": "run_v2_generated_revisions_list_revisions_sync.py", + "file": "run_v2_generated_revisions_list_revisions_sync_1d0f1802.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Revisions_ListRevisions_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": "run_v2_generated_revisions_list_revisions_sync_1d0f1802.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.RevisionsClient", + "shortName": "RevisionsClient" + }, + "fullName": "google.cloud.run_v2.RevisionsClient.list_revisions", + "method": { + "fullName": "google.cloud.run.v2.Revisions.ListRevisions", + "service": { + "fullName": "google.cloud.run.v2.Revisions", + "shortName": "Revisions" + }, + "shortName": "ListRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.ListRevisionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.run_v2.services.revisions.pagers.ListRevisionsPager", + "shortName": "list_revisions" + }, + "description": "Sample for ListRevisions", + "file": "run_v2_generated_revisions_list_revisions_sync_2312de2e.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Revisions_ListRevisions_sync", @@ -491,7 +731,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_revisions_list_revisions_sync.py" + "title": "run_v2_generated_revisions_list_revisions_sync_2312de2e.py" }, { "canonical": true, @@ -632,7 +872,7 @@ "shortName": "create_service" }, "description": "Sample for CreateService", - "file": "run_v2_generated_services_create_service_sync.py", + "file": "run_v2_generated_services_create_service_sync_3c405c33.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_CreateService_sync", @@ -668,42 +908,130 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_create_service_sync.py" + "title": "run_v2_generated_services_create_service_sync_3c405c33.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.run_v2.ServicesAsyncClient", - "shortName": "ServicesAsyncClient" + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" }, - "fullName": "google.cloud.run_v2.ServicesAsyncClient.delete_service", + "fullName": "google.cloud.run_v2.ServicesClient.create_service", "method": { - "fullName": "google.cloud.run.v2.Services.DeleteService", + "fullName": "google.cloud.run.v2.Services.CreateService", "service": { "fullName": "google.cloud.run.v2.Services", "shortName": "Services" }, - "shortName": "DeleteService" + "shortName": "CreateService" }, "parameters": [ { "name": "request", - "type": "google.cloud.run_v2.types.DeleteServiceRequest" + "type": "google.cloud.run_v2.types.CreateServiceRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" + "name": "service", + "type": "google.cloud.run_v2.types.Service" }, { - "name": "timeout", - "type": "float" - }, + "name": "service_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_service" + }, + "description": "Sample for CreateService", + "file": "run_v2_generated_services_create_service_sync_8031b824.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_CreateService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_create_service_sync_8031b824.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.ServicesAsyncClient", + "shortName": "ServicesAsyncClient" + }, + "fullName": "google.cloud.run_v2.ServicesAsyncClient.delete_service", + "method": { + "fullName": "google.cloud.run.v2.Services.DeleteService", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.DeleteServiceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, { "name": "metadata", "type": "Sequence[Tuple[str, str]" @@ -793,7 +1121,7 @@ "shortName": "delete_service" }, "description": "Sample for DeleteService", - "file": "run_v2_generated_services_delete_service_sync.py", + "file": "run_v2_generated_services_delete_service_sync_91d4ca21.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_DeleteService_sync", @@ -829,7 +1157,87 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_delete_service_sync.py" + "title": "run_v2_generated_services_delete_service_sync_91d4ca21.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.delete_service", + "method": { + "fullName": "google.cloud.run.v2.Services.DeleteService", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "DeleteService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.DeleteServiceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_service" + }, + "description": "Sample for DeleteService", + "file": "run_v2_generated_services_delete_service_sync_9c99d0a2.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_DeleteService_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_delete_service_sync_9c99d0a2.py" }, { "canonical": true, @@ -946,7 +1354,83 @@ "shortName": "get_iam_policy" }, "description": "Sample for GetIamPolicy", - "file": "run_v2_generated_services_get_iam_policy_sync.py", + "file": "run_v2_generated_services_get_iam_policy_sync_9f45c2a7.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_get_iam_policy_sync_9f45c2a7.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.run.v2.Services.GetIamPolicy", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "run_v2_generated_services_get_iam_policy_sync_449f2eb3.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_GetIamPolicy_sync", @@ -982,7 +1466,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_get_iam_policy_sync.py" + "title": "run_v2_generated_services_get_iam_policy_sync_449f2eb3.py" }, { "canonical": true, @@ -1026,19 +1510,260 @@ "resultType": "google.cloud.run_v2.types.Service", "shortName": "get_service" }, - "description": "Sample for GetService", - "file": "run_v2_generated_services_get_service_async.py", + "description": "Sample for GetService", + "file": "run_v2_generated_services_get_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_GetService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_get_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.get_service", + "method": { + "fullName": "google.cloud.run.v2.Services.GetService", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.GetServiceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.run_v2.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "run_v2_generated_services_get_service_sync_1c3ef02e.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_GetService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_get_service_sync_1c3ef02e.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.get_service", + "method": { + "fullName": "google.cloud.run.v2.Services.GetService", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "GetService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.GetServiceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.run_v2.types.Service", + "shortName": "get_service" + }, + "description": "Sample for GetService", + "file": "run_v2_generated_services_get_service_sync_18284d02.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_GetService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_get_service_sync_18284d02.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.run_v2.ServicesAsyncClient", + "shortName": "ServicesAsyncClient" + }, + "fullName": "google.cloud.run_v2.ServicesAsyncClient.list_services", + "method": { + "fullName": "google.cloud.run.v2.Services.ListServices", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "ListServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.ListServicesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.run_v2.services.services.pagers.ListServicesAsyncPager", + "shortName": "list_services" + }, + "description": "Sample for ListServices", + "file": "run_v2_generated_services_list_services_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "run_v2_generated_Services_GetService_async", + "regionTag": "run_v2_generated_Services_ListServices_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1058,12 +1783,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_get_service_async.py" + "title": "run_v2_generated_services_list_services_async.py" }, { "canonical": true, @@ -1072,22 +1797,22 @@ "fullName": "google.cloud.run_v2.ServicesClient", "shortName": "ServicesClient" }, - "fullName": "google.cloud.run_v2.ServicesClient.get_service", + "fullName": "google.cloud.run_v2.ServicesClient.list_services", "method": { - "fullName": "google.cloud.run.v2.Services.GetService", + "fullName": "google.cloud.run.v2.Services.ListServices", "service": { "fullName": "google.cloud.run.v2.Services", "shortName": "Services" }, - "shortName": "GetService" + "shortName": "ListServices" }, "parameters": [ { "name": "request", - "type": "google.cloud.run_v2.types.GetServiceRequest" + "type": "google.cloud.run_v2.types.ListServicesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1103,22 +1828,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.run_v2.types.Service", - "shortName": "get_service" + "resultType": "google.cloud.run_v2.services.services.pagers.ListServicesPager", + "shortName": "list_services" }, - "description": "Sample for GetService", - "file": "run_v2_generated_services_get_service_sync.py", + "description": "Sample for ListServices", + "file": "run_v2_generated_services_list_services_sync_c5743712.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "run_v2_generated_Services_GetService_sync", + "regionTag": "run_v2_generated_Services_ListServices_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1138,22 +1863,21 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_get_service_sync.py" + "title": "run_v2_generated_services_list_services_sync_c5743712.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.run_v2.ServicesAsyncClient", - "shortName": "ServicesAsyncClient" + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" }, - "fullName": "google.cloud.run_v2.ServicesAsyncClient.list_services", + "fullName": "google.cloud.run_v2.ServicesClient.list_services", "method": { "fullName": "google.cloud.run.v2.Services.ListServices", "service": { @@ -1184,14 +1908,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.run_v2.services.services.pagers.ListServicesAsyncPager", + "resultType": "google.cloud.run_v2.services.services.pagers.ListServicesPager", "shortName": "list_services" }, "description": "Sample for ListServices", - "file": "run_v2_generated_services_list_services_async.py", + "file": "run_v2_generated_services_list_services_sync_7dbaf490.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "run_v2_generated_Services_ListServices_async", + "regionTag": "run_v2_generated_Services_ListServices_sync", "segments": [ { "end": 52, @@ -1224,32 +1948,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_list_services_async.py" + "title": "run_v2_generated_services_list_services_sync_7dbaf490.py" }, { "canonical": true, "clientMethod": { + "async": true, "client": { - "fullName": "google.cloud.run_v2.ServicesClient", - "shortName": "ServicesClient" + "fullName": "google.cloud.run_v2.ServicesAsyncClient", + "shortName": "ServicesAsyncClient" }, - "fullName": "google.cloud.run_v2.ServicesClient.list_services", + "fullName": "google.cloud.run_v2.ServicesAsyncClient.set_iam_policy", "method": { - "fullName": "google.cloud.run.v2.Services.ListServices", + "fullName": "google.cloud.run.v2.Services.SetIamPolicy", "service": { "fullName": "google.cloud.run.v2.Services", "shortName": "Services" }, - "shortName": "ListServices" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.run_v2.types.ListServicesRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" }, { "name": "retry", @@ -1264,14 +1985,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.run_v2.services.services.pagers.ListServicesPager", - "shortName": "list_services" + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for ListServices", - "file": "run_v2_generated_services_list_services_sync.py", + "description": "Sample for SetIamPolicy", + "file": "run_v2_generated_services_set_iam_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "run_v2_generated_Services_ListServices_sync", + "regionTag": "run_v2_generated_Services_SetIamPolicy_async", "segments": [ { "end": 52, @@ -1284,37 +2005,36 @@ "type": "SHORT" }, { - "end": 40, - "start": 38, + "end": 41, + "start": 39, "type": "CLIENT_INITIALIZATION" }, { - "end": 45, - "start": 41, + "end": 46, + "start": 42, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_list_services_sync.py" + "title": "run_v2_generated_services_set_iam_policy_async.py" }, { "canonical": true, "clientMethod": { - "async": true, "client": { - "fullName": "google.cloud.run_v2.ServicesAsyncClient", - "shortName": "ServicesAsyncClient" + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" }, - "fullName": "google.cloud.run_v2.ServicesAsyncClient.set_iam_policy", + "fullName": "google.cloud.run_v2.ServicesClient.set_iam_policy", "method": { "fullName": "google.cloud.run.v2.Services.SetIamPolicy", "service": { @@ -1345,10 +2065,10 @@ "shortName": "set_iam_policy" }, "description": "Sample for SetIamPolicy", - "file": "run_v2_generated_services_set_iam_policy_async.py", + "file": "run_v2_generated_services_set_iam_policy_sync_c710ebbc.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "run_v2_generated_Services_SetIamPolicy_async", + "regionTag": "run_v2_generated_Services_SetIamPolicy_sync", "segments": [ { "end": 52, @@ -1381,7 +2101,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_set_iam_policy_async.py" + "title": "run_v2_generated_services_set_iam_policy_sync_c710ebbc.py" }, { "canonical": true, @@ -1421,7 +2141,7 @@ "shortName": "set_iam_policy" }, "description": "Sample for SetIamPolicy", - "file": "run_v2_generated_services_set_iam_policy_sync.py", + "file": "run_v2_generated_services_set_iam_policy_sync_b88666d6.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_SetIamPolicy_sync", @@ -1457,7 +2177,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_set_iam_policy_sync.py" + "title": "run_v2_generated_services_set_iam_policy_sync_b88666d6.py" }, { "canonical": true, @@ -1574,7 +2294,83 @@ "shortName": "test_iam_permissions" }, "description": "Sample for TestIamPermissions", - "file": "run_v2_generated_services_test_iam_permissions_sync.py", + "file": "run_v2_generated_services_test_iam_permissions_sync_048b00bc.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_test_iam_permissions_sync_048b00bc.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.run.v2.Services.TestIamPermissions", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_TestIamPermissions_sync", @@ -1610,7 +2406,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_test_iam_permissions_sync.py" + "title": "run_v2_generated_services_test_iam_permissions_sync_7c7fb79b.py" }, { "canonical": true, @@ -1735,7 +2531,87 @@ "shortName": "update_service" }, "description": "Sample for UpdateService", - "file": "run_v2_generated_services_update_service_sync.py", + "file": "run_v2_generated_services_update_service_sync_9076a854.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "run_v2_generated_Services_UpdateService_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "run_v2_generated_services_update_service_sync_9076a854.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.run_v2.ServicesClient", + "shortName": "ServicesClient" + }, + "fullName": "google.cloud.run_v2.ServicesClient.update_service", + "method": { + "fullName": "google.cloud.run.v2.Services.UpdateService", + "service": { + "fullName": "google.cloud.run.v2.Services", + "shortName": "Services" + }, + "shortName": "UpdateService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.run_v2.types.UpdateServiceRequest" + }, + { + "name": "service", + "type": "google.cloud.run_v2.types.Service" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_service" + }, + "description": "Sample for UpdateService", + "file": "run_v2_generated_services_update_service_sync_2652a462.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "run_v2_generated_Services_UpdateService_sync", @@ -1771,7 +2647,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "run_v2_generated_services_update_service_sync.py" + "title": "run_v2_generated_services_update_service_sync_2652a462.py" } ] } diff --git a/setup.py b/setup.py index 663d89c..353e4d6 100644 --- a/setup.py +++ b/setup.py @@ -26,10 +26,9 @@ release_status = "Development Status :: 4 - Beta" url = "https://github.com/googleapis/python-run" 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.0, <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", - "googleapis-common-protos >= 1.56.1, <2.0.0dev", + "protobuf >= 3.20.1, <5.0.0dev", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index e8e8a29..14eab6a 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -4,8 +4,7 @@ # 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.0 proto-plus==1.22.0 -googleapis-common-protos==1.56.1 grpc-google-iam-v1==0.12.4 -protobuf==3.19.0 +protobuf==3.20.1 diff --git a/tests/unit/gapic/run_v2/test_revisions.py b/tests/unit/gapic/run_v2/test_revisions.py index 5d484fc..c081633 100644 --- a/tests/unit/gapic/run_v2/test_revisions.py +++ b/tests/unit/gapic/run_v2/test_revisions.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api import launch_stage_pb2 # type: ignore from google.api_core import client_options @@ -101,6 +108,7 @@ def test__get_default_mtls_endpoint(): [ (RevisionsClient, "grpc"), (RevisionsAsyncClient, "grpc_asyncio"), + (RevisionsClient, "rest"), ], ) def test_revisions_client_from_service_account_info(client_class, transport_name): @@ -114,7 +122,11 @@ def test_revisions_client_from_service_account_info(client_class, transport_name assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) @pytest.mark.parametrize( @@ -122,6 +134,7 @@ def test_revisions_client_from_service_account_info(client_class, transport_name [ (transports.RevisionsGrpcTransport, "grpc"), (transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RevisionsRestTransport, "rest"), ], ) def test_revisions_client_service_account_always_use_jwt( @@ -147,6 +160,7 @@ def test_revisions_client_service_account_always_use_jwt( [ (RevisionsClient, "grpc"), (RevisionsAsyncClient, "grpc_asyncio"), + (RevisionsClient, "rest"), ], ) def test_revisions_client_from_service_account_file(client_class, transport_name): @@ -167,13 +181,18 @@ def test_revisions_client_from_service_account_file(client_class, transport_name assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) def test_revisions_client_get_transport_class(): transport = RevisionsClient.get_transport_class() available_transports = [ transports.RevisionsGrpcTransport, + transports.RevisionsRestTransport, ] assert transport in available_transports @@ -190,6 +209,7 @@ def test_revisions_client_get_transport_class(): transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", ), + (RevisionsClient, transports.RevisionsRestTransport, "rest"), ], ) @mock.patch.object( @@ -331,6 +351,8 @@ def test_revisions_client_client_options(client_class, transport_class, transpor "grpc_asyncio", "false", ), + (RevisionsClient, transports.RevisionsRestTransport, "rest", "true"), + (RevisionsClient, transports.RevisionsRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -524,6 +546,7 @@ def test_revisions_client_get_mtls_endpoint_and_cert_source(client_class): transports.RevisionsGrpcAsyncIOTransport, "grpc_asyncio", ), + (RevisionsClient, transports.RevisionsRestTransport, "rest"), ], ) def test_revisions_client_client_options_scopes( @@ -559,6 +582,7 @@ def test_revisions_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (RevisionsClient, transports.RevisionsRestTransport, "rest", None), ], ) def test_revisions_client_client_options_credentials_file( @@ -1486,6 +1510,919 @@ async def test_delete_revision_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + revision.GetRevisionRequest, + dict, + ], +) +def test_get_revision_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = revision.Revision( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service="service_value", + max_instance_request_concurrency=3436, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + encryption_key="encryption_key_value", + reconciling=True, + observed_generation=2021, + log_uri="log_uri_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = revision.Revision.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_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, revision.Revision) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service == "service_value" + assert response.max_instance_request_concurrency == 3436 + assert response.service_account == "service_account_value" + assert ( + response.execution_environment + == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1 + ) + assert response.encryption_key == "encryption_key_value" + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.log_uri == "log_uri_value" + assert response.etag == "etag_value" + + +def test_get_revision_rest_required_fields(request_type=revision.GetRevisionRequest): + transport_class = transports.RevisionsRestTransport + + 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_revision._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_revision._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 = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = revision.Revision() + # 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 = revision.Revision.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_revision(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_revision_rest_unset_required_fields(): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_revision_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(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.RevisionsRestInterceptor, "post_get_revision" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_get_revision" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.GetRevisionRequest.pb(revision.GetRevisionRequest()) + 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 = revision.Revision.to_json(revision.Revision()) + + request = revision.GetRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = revision.Revision() + + client.get_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_revision_rest_bad_request( + transport: str = "rest", request_type=revision.GetRevisionRequest +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_revision(request) + + +def test_get_revision_rest_flattened(): + client = RevisionsClient( + 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 = revision.Revision() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = revision.Revision.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_revision(**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/v2/{name=projects/*/locations/*/services/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_revision_rest_flattened_error(transport: str = "rest"): + client = RevisionsClient( + 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_revision( + revision.GetRevisionRequest(), + name="name_value", + ) + + +def test_get_revision_rest_error(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + revision.ListRevisionsRequest, + dict, + ], +) +def test_list_revisions_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/services/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 = revision.ListRevisionsResponse( + 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 = revision.ListRevisionsResponse.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_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_revisions_rest_required_fields( + request_type=revision.ListRevisionsRequest, +): + transport_class = transports.RevisionsRestTransport + + 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_revisions._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_revisions._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", + "show_deleted", + ) + ) + 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 = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = revision.ListRevisionsResponse() + # 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 = revision.ListRevisionsResponse.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_revisions(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_revisions_rest_unset_required_fields(): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_revisions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_revisions_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(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.RevisionsRestInterceptor, "post_list_revisions" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_list_revisions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.ListRevisionsRequest.pb(revision.ListRevisionsRequest()) + 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 = revision.ListRevisionsResponse.to_json( + revision.ListRevisionsResponse() + ) + + request = revision.ListRevisionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = revision.ListRevisionsResponse() + + client.list_revisions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_revisions_rest_bad_request( + transport: str = "rest", request_type=revision.ListRevisionsRequest +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/services/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_revisions(request) + + +def test_list_revisions_rest_flattened(): + client = RevisionsClient( + 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 = revision.ListRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/services/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = revision.ListRevisionsResponse.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_revisions(**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/v2/{parent=projects/*/locations/*/services/*}/revisions" + % client.transport._host, + args[1], + ) + + +def test_list_revisions_rest_flattened_error(transport: str = "rest"): + client = RevisionsClient( + 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_revisions( + revision.ListRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_revisions_rest_pager(transport: str = "rest"): + client = RevisionsClient( + 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 = ( + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + revision.Revision(), + ], + next_page_token="abc", + ), + revision.ListRevisionsResponse( + revisions=[], + next_page_token="def", + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + ], + next_page_token="ghi", + ), + revision.ListRevisionsResponse( + revisions=[ + revision.Revision(), + revision.Revision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(revision.ListRevisionsResponse.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/services/sample3" + } + + pager = client.list_revisions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, revision.Revision) for i in results) + + pages = list(client.list_revisions(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", + [ + revision.DeleteRevisionRequest, + dict, + ], +) +def test_delete_revision_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_revision(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_revision_rest_required_fields( + request_type=revision.DeleteRevisionRequest, +): + transport_class = transports.RevisionsRestTransport + + 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_revision._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_revision._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "validate_only", + ) + ) + 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 = RevisionsClient( + 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_revision(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_revision_rest_unset_required_fields(): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_revision._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_revision_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(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.RevisionsRestInterceptor, "post_delete_revision" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_delete_revision" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.DeleteRevisionRequest.pb(revision.DeleteRevisionRequest()) + 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 = revision.DeleteRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_revision_rest_bad_request( + transport: str = "rest", request_type=revision.DeleteRevisionRequest +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_revision(request) + + +def test_delete_revision_rest_flattened(): + client = RevisionsClient( + 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/services/sample3/revisions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_revision(**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/v2/{name=projects/*/locations/*/services/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_revision_rest_flattened_error(transport: str = "rest"): + client = RevisionsClient( + 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_revision( + revision.DeleteRevisionRequest(), + name="name_value", + ) + + +def test_delete_revision_rest_error(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RevisionsGrpcTransport( @@ -1567,6 +2504,7 @@ def test_transport_get_channel(): [ transports.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport, + transports.RevisionsRestTransport, ], ) def test_transport_adc(transport_class): @@ -1581,6 +2519,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1717,6 +2656,7 @@ def test_revisions_transport_auth_adc(transport_class): [ transports.RevisionsGrpcTransport, transports.RevisionsGrpcAsyncIOTransport, + transports.RevisionsRestTransport, ], ) def test_revisions_transport_auth_gdch_credentials(transport_class): @@ -1811,11 +2751,40 @@ def test_revisions_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_revisions_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.RevisionsRestTransport( + 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_revisions_rest_lro_client(): + client = RevisionsClient( + 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_revisions_host_no_port(transport_name): @@ -1824,7 +2793,11 @@ def test_revisions_host_no_port(transport_name): client_options=client_options.ClientOptions(api_endpoint="run.googleapis.com"), transport=transport_name, ) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) @pytest.mark.parametrize( @@ -1832,6 +2805,7 @@ def test_revisions_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_revisions_host_with_port(transport_name): @@ -1842,7 +2816,39 @@ def test_revisions_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("run.googleapis.com:8000") + assert client.transport._host == ( + "run.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_revisions_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RevisionsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RevisionsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_revision._session + session2 = client2.transport.get_revision._session + assert session1 != session2 + session1 = client1.transport.list_revisions._session + session2 = client2.transport.list_revisions._session + assert session1 != session2 + session1 = client1.transport.delete_revision._session + session2 = client2.transport.delete_revision._session + assert session1 != session2 def test_revisions_grpc_transport_channel(): @@ -2298,6 +3304,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2315,6 +3322,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/run_v2/test_services.py b/tests/unit/gapic/run_v2/test_services.py index 039f241..910dae2 100644 --- a/tests/unit/gapic/run_v2/test_services.py +++ b/tests/unit/gapic/run_v2/test_services.py @@ -24,10 +24,17 @@ import grpc from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule - +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format from google.api import launch_stage_pb2 # type: ignore from google.api_core import client_options @@ -109,6 +116,7 @@ def test__get_default_mtls_endpoint(): [ (ServicesClient, "grpc"), (ServicesAsyncClient, "grpc_asyncio"), + (ServicesClient, "rest"), ], ) def test_services_client_from_service_account_info(client_class, transport_name): @@ -122,7 +130,11 @@ def test_services_client_from_service_account_info(client_class, transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) @pytest.mark.parametrize( @@ -130,6 +142,7 @@ def test_services_client_from_service_account_info(client_class, transport_name) [ (transports.ServicesGrpcTransport, "grpc"), (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ServicesRestTransport, "rest"), ], ) def test_services_client_service_account_always_use_jwt( @@ -155,6 +168,7 @@ def test_services_client_service_account_always_use_jwt( [ (ServicesClient, "grpc"), (ServicesAsyncClient, "grpc_asyncio"), + (ServicesClient, "rest"), ], ) def test_services_client_from_service_account_file(client_class, transport_name): @@ -175,13 +189,18 @@ def test_services_client_from_service_account_file(client_class, transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) def test_services_client_get_transport_class(): transport = ServicesClient.get_transport_class() available_transports = [ transports.ServicesGrpcTransport, + transports.ServicesRestTransport, ] assert transport in available_transports @@ -194,6 +213,7 @@ def test_services_client_get_transport_class(): [ (ServicesClient, transports.ServicesGrpcTransport, "grpc"), (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (ServicesClient, transports.ServicesRestTransport, "rest"), ], ) @mock.patch.object( @@ -335,6 +355,8 @@ def test_services_client_client_options(client_class, transport_class, transport "grpc_asyncio", "false", ), + (ServicesClient, transports.ServicesRestTransport, "rest", "true"), + (ServicesClient, transports.ServicesRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -524,6 +546,7 @@ def test_services_client_get_mtls_endpoint_and_cert_source(client_class): [ (ServicesClient, transports.ServicesGrpcTransport, "grpc"), (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), + (ServicesClient, transports.ServicesRestTransport, "rest"), ], ) def test_services_client_client_options_scopes( @@ -559,6 +582,7 @@ def test_services_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (ServicesClient, transports.ServicesRestTransport, "rest", None), ], ) def test_services_client_client_options_credentials_file( @@ -2413,141 +2437,2708 @@ def test_test_iam_permissions_from_dict_foreign(): call.assert_called() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServicesGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + gcr_service.CreateServiceRequest, + dict, + ], +) +def test_create_service_rest(request_type): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["service"] = { + "name": "name_value", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "ingress": 1, + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "revision": "revision_value", + "labels": {}, + "annotations": {}, + "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, + "vpc_access": {"connector": "connector_value", "egress": 1}, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": {"limits": {}, "cpu_idle": True}, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + } + ], + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "max_instance_request_concurrency": 3436, + }, + "traffic": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + } + ], + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "latest_ready_revision": "latest_ready_revision_value", + "latest_created_revision": "latest_created_revision_value", + "traffic_statuses": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + "uri": "uri_value", + } + ], + "uri": "uri_value", + "reconciling": True, + "etag": "etag_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = 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_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_service_rest_required_fields( + request_type=gcr_service.CreateServiceRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_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, + ) ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + assert "serviceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == request_init["service_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["serviceId"] = "service_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "service_id", + "validate_only", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.ServicesGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == "service_id_value" + + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServicesClient( - client_options=options, - transport=transport, - ) + 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 - # 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 = ServicesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + 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_service(request) + + expected_params = [ + ( + "serviceId", + "", + ), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "serviceId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "service", + "serviceId", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.ServicesGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = ServicesClient(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.ServicesRestInterceptor, "post_create_service" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_create_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcr_service.CreateServiceRequest.pb( + gcr_service.CreateServiceRequest() + ) + 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 = gcr_service.CreateServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( + client.create_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_service_rest_bad_request( + transport: str = "rest", request_type=gcr_service.CreateServiceRequest +): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = ServicesClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["service"] = { + "name": "name_value", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "ingress": 1, + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "revision": "revision_value", + "labels": {}, + "annotations": {}, + "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, + "vpc_access": {"connector": "connector_value", "egress": 1}, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": {"limits": {}, "cpu_idle": True}, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + } + ], + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "max_instance_request_concurrency": 3436, + }, + "traffic": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + } + ], + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "latest_ready_revision": "latest_ready_revision_value", + "latest_created_revision": "latest_created_revision_value", + "traffic_statuses": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + "uri": "uri_value", + } + ], + "uri": "uri_value", + "reconciling": True, + "etag": "etag_value", + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( + # 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_service(request) + + +def test_create_service_rest_flattened(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ServicesGrpcAsyncIOTransport( + # 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", + service=gcr_service.Service(name="name_value"), + service_id="service_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_service(**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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, + args[1], + ) + + +def test_create_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_service( + gcr_service.CreateServiceRequest(), + parent="parent_value", + service=gcr_service.Service(name="name_value"), + service_id="service_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, - ], -) -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() +def test_create_service_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.GetServiceRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = ServicesClient.get_transport_class(transport_name)( +def test_get_service_rest(request_type): + client = ServicesClient( 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/services/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.Service( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + latest_ready_revision="latest_ready_revision_value", + latest_created_revision="latest_created_revision_value", + uri="uri_value", + reconciling=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Service.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_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.observed_generation == 2021 + assert response.latest_ready_revision == "latest_ready_revision_value" + assert response.latest_created_revision == "latest_created_revision_value" + assert response.uri == "uri_value" + assert response.reconciling is True + assert response.etag == "etag_value" + + +def test_get_service_rest_required_fields(request_type=service.GetServiceRequest): + transport_class = transports.ServicesRestTransport + + 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_service._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_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.ServicesGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Service() + # 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.Service.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_service(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_services_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_service_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_get_service" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_get_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetServiceRequest.pb(service.GetServiceRequest()) + 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.Service.to_json(service.Service()) + + request = service.GetServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Service() -def test_services_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.run_v2.services.services.transports.ServicesTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.get_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly + pre.assert_called_once() + post.assert_called_once() + + +def test_get_service_rest_bad_request( + transport: str = "rest", request_type=service.GetServiceRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/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_service(request) + + +def test_get_service_rest_flattened(): + client = ServicesClient( + 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.Service() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/services/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 = service.Service.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_service(**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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, + args[1], + ) + + +def test_get_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + service.GetServiceRequest(), + name="name_value", + ) + + +def test_get_service_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListServicesRequest, + dict, + ], +) +def test_list_services_rest(request_type): + client = ServicesClient( + 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 = service.ListServicesResponse( + 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.ListServicesResponse.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_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_services_rest_required_fields(request_type=service.ListServicesRequest): + transport_class = transports.ServicesRestTransport + + 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_services._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_services._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", + "show_deleted", + ) + ) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListServicesResponse() + # 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.ListServicesResponse.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_services(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_services_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_services._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_services_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_list_services" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_list_services" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListServicesRequest.pb(service.ListServicesRequest()) + 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.ListServicesResponse.to_json( + service.ListServicesResponse() + ) + + request = service.ListServicesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListServicesResponse() + + client.list_services( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_services_rest_bad_request( + transport: str = "rest", request_type=service.ListServicesRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_services(request) + + +def test_list_services_rest_flattened(): + client = ServicesClient( + 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.ListServicesResponse() + + # 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.ListServicesResponse.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_services(**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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, + args[1], + ) + + +def test_list_services_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_services( + service.ListServicesRequest(), + parent="parent_value", + ) + + +def test_list_services_rest_pager(transport: str = "rest"): + client = ServicesClient( + 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.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token="abc", + ), + service.ListServicesResponse( + services=[], + next_page_token="def", + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token="ghi", + ), + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListServicesResponse.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_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.Service) for i in results) + + pages = list(client.list_services(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", + [ + gcr_service.UpdateServiceRequest, + dict, + ], +) +def test_update_service_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "service": {"name": "projects/sample1/locations/sample2/services/sample3"} + } + request_init["service"] = { + "name": "projects/sample1/locations/sample2/services/sample3", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "ingress": 1, + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "revision": "revision_value", + "labels": {}, + "annotations": {}, + "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, + "vpc_access": {"connector": "connector_value", "egress": 1}, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": {"limits": {}, "cpu_idle": True}, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + } + ], + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "max_instance_request_concurrency": 3436, + }, + "traffic": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + } + ], + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "latest_ready_revision": "latest_ready_revision_value", + "latest_created_revision": "latest_created_revision_value", + "traffic_statuses": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + "uri": "uri_value", + } + ], + "uri": "uri_value", + "reconciling": True, + "etag": "etag_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = 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_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_service_rest_required_fields( + request_type=gcr_service.UpdateServiceRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ServicesClient( + 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_service(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "validateOnly", + ) + ) + & set(("service",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_service_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_update_service" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_update_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcr_service.UpdateServiceRequest.pb( + gcr_service.UpdateServiceRequest() + ) + 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 = gcr_service.UpdateServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_service_rest_bad_request( + transport: str = "rest", request_type=gcr_service.UpdateServiceRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "service": {"name": "projects/sample1/locations/sample2/services/sample3"} + } + request_init["service"] = { + "name": "projects/sample1/locations/sample2/services/sample3", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "ingress": 1, + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "revision": "revision_value", + "labels": {}, + "annotations": {}, + "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, + "vpc_access": {"connector": "connector_value", "egress": 1}, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": {"limits": {}, "cpu_idle": True}, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + } + ], + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "max_instance_request_concurrency": 3436, + }, + "traffic": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + } + ], + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "latest_ready_revision": "latest_ready_revision_value", + "latest_created_revision": "latest_created_revision_value", + "traffic_statuses": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + "uri": "uri_value", + } + ], + "uri": "uri_value", + "reconciling": True, + "etag": "etag_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_service(request) + + +def test_update_service_rest_flattened(): + client = ServicesClient( + 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 = { + "service": {"name": "projects/sample1/locations/sample2/services/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + service=gcr_service.Service(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.update_service(**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/v2/{service.name=projects/*/locations/*/services/*}" + % client.transport._host, + args[1], + ) + + +def test_update_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + gcr_service.UpdateServiceRequest(), + service=gcr_service.Service(name="name_value"), + ) + + +def test_update_service_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteServiceRequest, + dict, + ], +) +def test_delete_service_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/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_service(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_service_rest_required_fields(request_type=service.DeleteServiceRequest): + transport_class = transports.ServicesRestTransport + + 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_service._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_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "validate_only", + ) + ) + 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 = ServicesClient( + 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_service(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_service_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_delete_service" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_delete_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteServiceRequest.pb(service.DeleteServiceRequest()) + 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.DeleteServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_service_rest_bad_request( + transport: str = "rest", request_type=service.DeleteServiceRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/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_service(request) + + +def test_delete_service_rest_flattened(): + client = ServicesClient( + 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/services/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_service(**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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, + args[1], + ) + + +def test_delete_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + service.DeleteServiceRequest(), + name="name_value", + ) + + +def test_delete_service_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = 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_iam_policy._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() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options",)) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + 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 = 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_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("options",)) & set(("resource",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + 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(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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_iam_policy(request) + + +def test_get_iam_policy_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = 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() + ).set_iam_policy._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() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = 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.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "policy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + 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(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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.set_iam_policy(request) + + +def test_set_iam_policy_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = 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() + ).test_iam_permissions._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" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + 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 "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # 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 + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = 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.test_iam_permissions(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(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.ServicesRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + 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( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_error(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServicesClient( + 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 = ServicesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServicesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, + transports.ServicesRestTransport, + ], +) +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 = ServicesClient.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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServicesGrpcTransport, + ) + + +def test_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_services_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.run_v2.services.services.transports.ServicesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "create_service", @@ -2649,6 +5240,7 @@ def test_services_transport_auth_adc(transport_class): [ transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport, + transports.ServicesRestTransport, ], ) def test_services_transport_auth_gdch_credentials(transport_class): @@ -2743,11 +5335,40 @@ def test_services_grpc_transport_client_cert_source_for_mtls(transport_class): ) +def test_services_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.ServicesRestTransport( + 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_services_rest_lro_client(): + client = ServicesClient( + 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_services_host_no_port(transport_name): @@ -2756,7 +5377,11 @@ def test_services_host_no_port(transport_name): client_options=client_options.ClientOptions(api_endpoint="run.googleapis.com"), transport=transport_name, ) - assert client.transport._host == ("run.googleapis.com:443") + assert client.transport._host == ( + "run.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com" + ) @pytest.mark.parametrize( @@ -2764,6 +5389,7 @@ def test_services_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_services_host_with_port(transport_name): @@ -2774,7 +5400,54 @@ def test_services_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("run.googleapis.com:8000") + assert client.transport._host == ( + "run.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://run.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_services_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ServicesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ServicesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_service._session + session2 = client2.transport.create_service._session + assert session1 != session2 + session1 = client1.transport.get_service._session + session2 = client2.transport.get_service._session + assert session1 != session2 + session1 = client1.transport.list_services._session + session2 = client2.transport.list_services._session + assert session1 != session2 + session1 = client1.transport.update_service._session + session2 = client2.transport.update_service._session + assert session1 != session2 + session1 = client1.transport.delete_service._session + session2 = client2.transport.delete_service._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 def test_services_grpc_transport_channel(): @@ -3230,6 +5903,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3247,6 +5921,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: