diff --git a/packages/google-cloud-functions/.github/workflows/unittest.yml b/packages/google-cloud-functions/.github/workflows/unittest.yml index 5531b0141297..f76daebffda7 100644 --- a/packages/google-cloud-functions/.github/workflows/unittest.yml +++ b/packages/google-cloud-functions/.github/workflows/unittest.yml @@ -54,4 +54,4 @@ jobs: - name: Report coverage results run: | coverage combine .coverage-results/.coverage* - coverage report --show-missing --fail-under=100 + coverage report --show-missing --fail-under=99 diff --git a/packages/google-cloud-functions/docs/functions_v2/function_service.rst b/packages/google-cloud-functions/docs/functions_v2/function_service.rst new file mode 100644 index 000000000000..03a513276d6a --- /dev/null +++ b/packages/google-cloud-functions/docs/functions_v2/function_service.rst @@ -0,0 +1,10 @@ +FunctionService +--------------------------------- + +.. automodule:: google.cloud.functions_v2.services.function_service + :members: + :inherited-members: + +.. automodule:: google.cloud.functions_v2.services.function_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-functions/docs/functions_v2/services.rst b/packages/google-cloud-functions/docs/functions_v2/services.rst new file mode 100644 index 000000000000..a2004da21794 --- /dev/null +++ b/packages/google-cloud-functions/docs/functions_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Functions v2 API +========================================== +.. toctree:: + :maxdepth: 2 + + function_service diff --git a/packages/google-cloud-functions/docs/functions_v2/types.rst b/packages/google-cloud-functions/docs/functions_v2/types.rst new file mode 100644 index 000000000000..f708365f672c --- /dev/null +++ b/packages/google-cloud-functions/docs/functions_v2/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Functions v2 API +======================================= + +.. automodule:: google.cloud.functions_v2.types + :members: + :undoc-members: + :show-inheritance: diff --git a/packages/google-cloud-functions/docs/index.rst b/packages/google-cloud-functions/docs/index.rst index 7537b901dd5a..15bb7cd0895b 100644 --- a/packages/google-cloud-functions/docs/index.rst +++ b/packages/google-cloud-functions/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Cloud Functions. +By default, you will get version ``functions_v1``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference functions_v1/services functions_v1/types +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + functions_v2/services + functions_v2/types + Changelog --------- diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/client.py b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/client.py index 7e281926194a..62c6d5f89f35 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/client.py @@ -483,6 +483,7 @@ def __init__( quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, + api_audience=client_options.api_audience, ) def list_functions( diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py index 7d8f267231db..43ebae93e935 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py @@ -57,6 +57,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -84,11 +85,6 @@ def __init__( be used for service account credentials. """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} # Save the scopes. @@ -109,6 +105,11 @@ def __init__( credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. if ( @@ -121,6 +122,11 @@ def __init__( # Save the credentials. self._credentials = credentials + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py index 787b6e7b7cc1..777cbcb9d161 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -157,6 +158,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py index 96fdadebd1d6..818f79d16f12 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py @@ -106,6 +106,7 @@ def __init__( quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, ) -> None: """Instantiate the transport. @@ -202,6 +203,7 @@ def __init__( quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, ) if not self._grpc_channel: diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/__init__.py b/packages/google-cloud-functions/google/cloud/functions_v2/__init__.py new file mode 100644 index 000000000000..8810a8152670 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/__init__.py @@ -0,0 +1,78 @@ +# -*- 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 .services.function_service import FunctionServiceAsyncClient, FunctionServiceClient +from .types.functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + Environment, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, +) + +__all__ = ( + "FunctionServiceAsyncClient", + "BuildConfig", + "CreateFunctionRequest", + "DeleteFunctionRequest", + "Environment", + "EventFilter", + "EventTrigger", + "Function", + "FunctionServiceClient", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "RepoSource", + "SecretEnvVar", + "SecretVolume", + "ServiceConfig", + "Source", + "SourceProvenance", + "Stage", + "StateMessage", + "StorageSource", + "UpdateFunctionRequest", +) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/gapic_metadata.json b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_metadata.json new file mode 100644 index 000000000000..a8aa8cbf2fa7 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.functions_v2", + "protoPackage": "google.cloud.functions.v2", + "schema": "1.0", + "services": { + "FunctionService": { + "clients": { + "grpc": { + "libraryClient": "FunctionServiceClient", + "rpcs": { + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "ListRuntimes": { + "methods": [ + "list_runtimes" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FunctionServiceAsyncClient", + "rpcs": { + "CreateFunction": { + "methods": [ + "create_function" + ] + }, + "DeleteFunction": { + "methods": [ + "delete_function" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "generate_download_url" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "generate_upload_url" + ] + }, + "GetFunction": { + "methods": [ + "get_function" + ] + }, + "ListFunctions": { + "methods": [ + "list_functions" + ] + }, + "ListRuntimes": { + "methods": [ + "list_runtimes" + ] + }, + "UpdateFunction": { + "methods": [ + "update_function" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/py.typed b/packages/google-cloud-functions/google/cloud/functions_v2/py.typed new file mode 100644 index 000000000000..982ebb18c324 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-functions package uses inline types. diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/__init__.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/__init__.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/__init__.py new file mode 100644 index 000000000000..73f00d9363ee --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 .async_client import FunctionServiceAsyncClient +from .client import FunctionServiceClient + +__all__ = ( + "FunctionServiceClient", + "FunctionServiceAsyncClient", +) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/async_client.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/async_client.py new file mode 100644 index 000000000000..be012416f32e --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/async_client.py @@ -0,0 +1,1572 @@ +# -*- 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 collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + +from .client import FunctionServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + + +class FunctionServiceAsyncClient: + """Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + """ + + _client: FunctionServiceClient + + DEFAULT_ENDPOINT = FunctionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FunctionServiceClient.DEFAULT_MTLS_ENDPOINT + + build_path = staticmethod(FunctionServiceClient.build_path) + parse_build_path = staticmethod(FunctionServiceClient.parse_build_path) + channel_path = staticmethod(FunctionServiceClient.channel_path) + parse_channel_path = staticmethod(FunctionServiceClient.parse_channel_path) + connector_path = staticmethod(FunctionServiceClient.connector_path) + parse_connector_path = staticmethod(FunctionServiceClient.parse_connector_path) + function_path = staticmethod(FunctionServiceClient.function_path) + parse_function_path = staticmethod(FunctionServiceClient.parse_function_path) + repository_path = staticmethod(FunctionServiceClient.repository_path) + parse_repository_path = staticmethod(FunctionServiceClient.parse_repository_path) + service_path = staticmethod(FunctionServiceClient.service_path) + parse_service_path = staticmethod(FunctionServiceClient.parse_service_path) + topic_path = staticmethod(FunctionServiceClient.topic_path) + parse_topic_path = staticmethod(FunctionServiceClient.parse_topic_path) + trigger_path = staticmethod(FunctionServiceClient.trigger_path) + parse_trigger_path = staticmethod(FunctionServiceClient.parse_trigger_path) + worker_pool_path = staticmethod(FunctionServiceClient.worker_pool_path) + parse_worker_pool_path = staticmethod(FunctionServiceClient.parse_worker_pool_path) + common_billing_account_path = staticmethod( + FunctionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + FunctionServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(FunctionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + FunctionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + FunctionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + FunctionServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(FunctionServiceClient.common_project_path) + parse_common_project_path = staticmethod( + FunctionServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(FunctionServiceClient.common_location_path) + parse_common_location_path = staticmethod( + FunctionServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FunctionServiceAsyncClient: The constructed client. + """ + return FunctionServiceClient.from_service_account_info.__func__(FunctionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FunctionServiceAsyncClient: The constructed client. + """ + return FunctionServiceClient.from_service_account_file.__func__(FunctionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return FunctionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> FunctionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FunctionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(FunctionServiceClient).get_transport_class, type(FunctionServiceClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FunctionServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the function service client. + + Args: + 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. + transport (Union[str, ~.FunctionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + 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 + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FunctionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_function( + self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (:class:`str`): + Required. The name of the function + which details should be obtained. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.types.Function: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulates + function and trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.GetFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_function, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_functions( + self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsAsyncPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + method. + parent (:class:`str`): + Required. The project and location from which the + function should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions + in all locations, use "-" in place of a location. When + listing functions in all locations, if one or more + location(s) are unreachable, the response will contain + functions from all reachable locations along with the + names of any unreachable locations. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.services.function_service.pagers.ListFunctionsAsyncPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.ListFunctionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_functions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFunctionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_function( + self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + parent (:class:`str`): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (:class:`google.cloud.functions_v2.types.Function`): + Required. Function to be created. + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function_id (:class:`str`): + The ID to use for the function, which will become the + final component of the function's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``function_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, function, function_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.CreateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if function is not None: + request.function = function + if function_id is not None: + request.function_id = function_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_function, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_function( + self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (:class:`google.cloud.functions_v2.types.Function`): + Required. New version of the + function. + + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + If no field mask is provided, all + provided fields in the request will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([function, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.UpdateFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_function, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("function.name", request.function.name),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_function( + self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (:class:`str`): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.DeleteFunctionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_function, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_upload_url( + self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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: + google.cloud.functions_v2.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_upload_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_download_url( + self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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: + google.cloud.functions_v2.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_download_url, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_runtimes( + self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: + r"""Returns a list of runtimes that are supported for the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + async def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_runtimes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListRuntimesRequest, dict]): + The request object. Request for the `ListRuntimes` + method. + parent (:class:`str`): + Required. The project and location from which the + runtimes should be listed, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.types.ListRuntimesResponse: + Response for the ListRuntimes method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = functions.ListRuntimesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_runtimes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.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: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. JSON Example. + + .. code-block:: python + + { + "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')", + } + } + ] + } + + **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') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.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: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. JSON Example. + + .. code-block:: python + + { + "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')", + } + } + ] + } + + **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') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.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. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FunctionServiceAsyncClient",) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/client.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/client.py new file mode 100644 index 000000000000..f09c5cb68ed6 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/client.py @@ -0,0 +1,1965 @@ +# -*- 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 collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.functions_v2.services.function_service import pagers +from google.cloud.functions_v2.types import functions + +from .transports.base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .transports.grpc import FunctionServiceGrpcTransport +from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + + +class FunctionServiceClientMeta(type): + """Metaclass for the FunctionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[FunctionServiceTransport]] + _transport_registry["grpc"] = FunctionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = FunctionServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: str = None, + ) -> Type[FunctionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class FunctionServiceClient(metaclass=FunctionServiceClientMeta): + """Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudfunctions.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FunctionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FunctionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FunctionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FunctionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def build_path( + project: str, + location: str, + build: str, + ) -> str: + """Returns a fully-qualified build string.""" + return "projects/{project}/locations/{location}/builds/{build}".format( + project=project, + location=location, + build=build, + ) + + @staticmethod + def parse_build_path(path: str) -> Dict[str, str]: + """Parses a build path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/builds/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def channel_path( + project: str, + location: str, + channel: str, + ) -> str: + """Returns a fully-qualified channel string.""" + return "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) + + @staticmethod + def parse_channel_path(path: str) -> Dict[str, str]: + """Parses a channel path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def connector_path( + project: str, + location: str, + connector: str, + ) -> str: + """Returns a fully-qualified connector string.""" + return "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) + + @staticmethod + def parse_connector_path(path: str) -> Dict[str, str]: + """Parses a connector path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/connectors/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def function_path( + project: str, + location: str, + function: str, + ) -> str: + """Returns a fully-qualified function string.""" + return "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) + + @staticmethod + def parse_function_path(path: str) -> Dict[str, str]: + """Parses a function path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def repository_path( + project: str, + location: str, + repository: str, + ) -> str: + """Returns a fully-qualified repository string.""" + return ( + "projects/{project}/locations/{location}/repositories/{repository}".format( + project=project, + location=location, + repository=repository, + ) + ) + + @staticmethod + def parse_repository_path(path: str) -> Dict[str, str]: + """Parses a repository path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/repositories/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path( + project: str, + location: str, + service: str, + ) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def topic_path( + project: str, + topic: str, + ) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str, str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def trigger_path( + project: str, + location: str, + trigger: str, + ) -> str: + """Returns a fully-qualified trigger string.""" + return "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) + + @staticmethod + def parse_trigger_path(path: str) -> Dict[str, str]: + """Parses a trigger path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def worker_pool_path( + project: str, + location: str, + worker_pool: str, + ) -> str: + """Returns a fully-qualified worker_pool string.""" + return ( + "projects/{project}/locations/{location}/workerPools/{worker_pool}".format( + project=project, + location=location, + worker_pool=worker_pool, + ) + ) + + @staticmethod + def parse_worker_pool_path(path: str) -> Dict[str, str]: + """Parses a worker_pool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FunctionServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the function service client. + + Args: + 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. + transport (Union[str, FunctionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + 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 + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + 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're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FunctionServiceTransport): + # transport is a FunctionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_function( + self, + request: Union[functions.GetFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.Function: + r"""Returns a function with the given name from the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GetFunctionRequest, dict]): + The request object. Request for the `GetFunction` + method. + name (str): + Required. The name of the function + which details should be obtained. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.types.Function: + Describes a Cloud Function that + contains user computation executed in + response to an event. It encapsulates + function and trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.GetFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GetFunctionRequest): + request = functions.GetFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_functions( + self, + request: Union[functions.ListFunctionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFunctionsPager: + r"""Returns a list of functions that belong to the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListFunctionsRequest, dict]): + The request object. Request for the `ListFunctions` + method. + parent (str): + Required. The project and location from which the + function should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions + in all locations, use "-" in place of a location. When + listing functions in all locations, if one or more + location(s) are unreachable, the response will contain + functions from all reachable locations along with the + names of any unreachable locations. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.services.function_service.pagers.ListFunctionsPager: + Response for the ListFunctions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListFunctionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListFunctionsRequest): + request = functions.ListFunctionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_functions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFunctionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_function( + self, + request: Union[functions.CreateFunctionRequest, dict] = None, + *, + parent: str = None, + function: functions.Function = None, + function_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.CreateFunctionRequest, dict]): + The request object. Request for the `CreateFunction` + method. + parent (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function (google.cloud.functions_v2.types.Function): + Required. Function to be created. + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + function_id (str): + The ID to use for the function, which will become the + final component of the function's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + This corresponds to the ``function_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, function, function_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.CreateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.CreateFunctionRequest): + request = functions.CreateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if function is not None: + request.function = function + if function_id is not None: + request.function_id = function_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_function( + self, + request: Union[functions.UpdateFunctionRequest, dict] = None, + *, + function: functions.Function = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates existing function. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.UpdateFunctionRequest, dict]): + The request object. Request for the `UpdateFunction` + method. + function (google.cloud.functions_v2.types.Function): + Required. New version of the + function. + + This corresponds to the ``function`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If no field mask is provided, all + provided fields in the request will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.functions_v2.types.Function` Describes a Cloud Function that contains user computation executed in + response to an event. It encapsulates function and + trigger configurations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([function, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.UpdateFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.UpdateFunctionRequest): + request = functions.UpdateFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if function is not None: + request.function = function + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("function.name", request.function.name),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + functions.Function, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_function( + self, + request: Union[functions.DeleteFunctionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.DeleteFunctionRequest, dict]): + The request object. Request for the `DeleteFunction` + method. + name (str): + Required. The name of the function + which should be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.DeleteFunctionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.DeleteFunctionRequest): + request = functions.DeleteFunctionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_function] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=functions.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_upload_url( + self, + request: Union[functions.GenerateUploadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateUploadUrlResponse: + r"""Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateUploadUrlRequest, dict]): + The request object. Request of `GenerateSourceUploadUrl` + 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: + google.cloud.functions_v2.types.GenerateUploadUrlResponse: + Response of GenerateSourceUploadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateUploadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateUploadUrlRequest): + request = functions.GenerateUploadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_upload_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_download_url( + self, + request: Union[functions.GenerateDownloadUrlRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.GenerateDownloadUrlResponse: + r"""Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.GenerateDownloadUrlRequest, dict]): + The request object. Request of `GenerateDownloadUrl` + 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: + google.cloud.functions_v2.types.GenerateDownloadUrlResponse: + Response of GenerateDownloadUrl method. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a functions.GenerateDownloadUrlRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.GenerateDownloadUrlRequest): + request = functions.GenerateDownloadUrlRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_download_url] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_runtimes( + self, + request: Union[functions.ListRuntimesRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> functions.ListRuntimesResponse: + r"""Returns a list of runtimes that are supported for the + requested project. + + .. code-block:: python + + from google.cloud import functions_v2 + + def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_runtimes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.functions_v2.types.ListRuntimesRequest, dict]): + The request object. Request for the `ListRuntimes` + method. + parent (str): + Required. The project and location from which the + runtimes should be listed, specified in the format + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.functions_v2.types.ListRuntimesResponse: + Response for the ListRuntimes method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a functions.ListRuntimesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, functions.ListRuntimesRequest): + request = functions.ListRuntimesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_runtimes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.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: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. JSON Example. + + .. code-block:: python + + { + "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')", + } + } + ] + } + + **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') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.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: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. JSON Example. + + .. code-block:: python + + { + "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')", + } + } + ] + } + + **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') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.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. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_locations( + self, + request: locations_pb2.ListLocationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FunctionServiceClient",) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/pagers.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/pagers.py new file mode 100644 index 000000000000..08de65745cff --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/pagers.py @@ -0,0 +1,155 @@ +# -*- 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.functions_v2.types import functions + + +class ListFunctionsPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v2.types.ListFunctionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v2.types.ListFunctionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., functions.ListFunctionsResponse], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.functions_v2.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v2.types.ListFunctionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[functions.ListFunctionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[functions.Function]: + for page in self.pages: + yield from page.functions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFunctionsAsyncPager: + """A pager for iterating through ``list_functions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.functions_v2.types.ListFunctionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``functions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFunctions`` requests and continue to iterate + through the ``functions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.functions_v2.types.ListFunctionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[functions.ListFunctionsResponse]], + request: functions.ListFunctionsRequest, + response: functions.ListFunctionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.functions_v2.types.ListFunctionsRequest): + The initial request object. + response (google.cloud.functions_v2.types.ListFunctionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = functions.ListFunctionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[functions.ListFunctionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[functions.Function]: + async def async_generator(): + async for page in self.pages: + for response in page.functions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/__init__.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/__init__.py new file mode 100644 index 000000000000..cc0b2072f44b --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- 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 collections import OrderedDict +from typing import Dict, Type + +from .base import FunctionServiceTransport +from .grpc import FunctionServiceGrpcTransport +from .grpc_asyncio import FunctionServiceGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] +_transport_registry["grpc"] = FunctionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = FunctionServiceGrpcAsyncIOTransport + +__all__ = ( + "FunctionServiceTransport", + "FunctionServiceGrpcTransport", + "FunctionServiceGrpcAsyncIOTransport", +) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/base.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/base.py new file mode 100644 index 000000000000..ab49afa88984 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/base.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +from google.cloud.functions_v2.types import functions + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-functions", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class FunctionServiceTransport(abc.ABC): + """Abstract transport class for FunctionService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudfunctions.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_function: gapic_v1.method.wrap_method( + self.get_function, + default_timeout=None, + client_info=client_info, + ), + self.list_functions: gapic_v1.method.wrap_method( + self.list_functions, + default_timeout=None, + client_info=client_info, + ), + self.create_function: gapic_v1.method.wrap_method( + self.create_function, + default_timeout=None, + client_info=client_info, + ), + self.update_function: gapic_v1.method.wrap_method( + self.update_function, + default_timeout=None, + client_info=client_info, + ), + self.delete_function: gapic_v1.method.wrap_method( + self.delete_function, + default_timeout=None, + client_info=client_info, + ), + self.generate_upload_url: gapic_v1.method.wrap_method( + self.generate_upload_url, + default_timeout=None, + client_info=client_info, + ), + self.generate_download_url: gapic_v1.method.wrap_method( + self.generate_download_url, + default_timeout=None, + client_info=client_info, + ), + self.list_runtimes: gapic_v1.method.wrap_method( + self.list_runtimes, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_function( + self, + ) -> Callable[ + [functions.GetFunctionRequest], + Union[functions.Function, Awaitable[functions.Function]], + ]: + raise NotImplementedError() + + @property + def list_functions( + self, + ) -> Callable[ + [functions.ListFunctionsRequest], + Union[ + functions.ListFunctionsResponse, Awaitable[functions.ListFunctionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def create_function( + self, + ) -> Callable[ + [functions.CreateFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_function( + self, + ) -> Callable[ + [functions.UpdateFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_function( + self, + ) -> Callable[ + [functions.DeleteFunctionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], + Union[ + functions.GenerateUploadUrlResponse, + Awaitable[functions.GenerateUploadUrlResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Union[ + functions.GenerateDownloadUrlResponse, + Awaitable[functions.GenerateDownloadUrlResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_runtimes( + self, + ) -> Callable[ + [functions.ListRuntimesRequest], + Union[ + functions.ListRuntimesResponse, Awaitable[functions.ListRuntimesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("FunctionServiceTransport",) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc.py new file mode 100644 index 000000000000..668762f87e07 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc.py @@ -0,0 +1,648 @@ +# -*- 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport + + +class FunctionServiceGrpcTransport(FunctionServiceTransport): + """gRPC backend transport for FunctionService. + + Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudfunctions.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudfunctions.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def get_function( + self, + ) -> Callable[[functions.GetFunctionRequest], functions.Function]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + ~.Function]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_function" not in self._stubs: + self._stubs["get_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GetFunction", + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.Function.deserialize, + ) + return self._stubs["get_function"] + + @property + def list_functions( + self, + ) -> Callable[[functions.ListFunctionsRequest], functions.ListFunctionsResponse]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + ~.ListFunctionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_functions" not in self._stubs: + self._stubs["list_functions"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListFunctions", + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs["list_functions"] + + @property + def create_function( + self, + ) -> Callable[[functions.CreateFunctionRequest], operations_pb2.Operation]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_function" not in self._stubs: + self._stubs["create_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/CreateFunction", + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_function"] + + @property + def update_function( + self, + ) -> Callable[[functions.UpdateFunctionRequest], operations_pb2.Operation]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_function" not in self._stubs: + self._stubs["update_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/UpdateFunction", + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_function"] + + @property + def delete_function( + self, + ) -> Callable[[functions.DeleteFunctionRequest], operations_pb2.Operation]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_function" not in self._stubs: + self._stubs["delete_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/DeleteFunction", + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_function"] + + @property + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], functions.GenerateUploadUrlResponse + ]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + ~.GenerateUploadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_upload_url" not in self._stubs: + self._stubs["generate_upload_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateUploadUrl", + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs["generate_upload_url"] + + @property + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], functions.GenerateDownloadUrlResponse + ]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + ~.GenerateDownloadUrlResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_download_url" not in self._stubs: + self._stubs["generate_download_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl", + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs["generate_download_url"] + + @property + def list_runtimes( + self, + ) -> Callable[[functions.ListRuntimesRequest], functions.ListRuntimesResponse]: + r"""Return a callable for the list runtimes method over gRPC. + + Returns a list of runtimes that are supported for the + requested project. + + Returns: + Callable[[~.ListRuntimesRequest], + ~.ListRuntimesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_runtimes" not in self._stubs: + self._stubs["list_runtimes"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListRuntimes", + request_serializer=functions.ListRuntimesRequest.serialize, + response_deserializer=functions.ListRuntimesResponse.deserialize, + ) + return self._stubs["list_runtimes"] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("FunctionServiceGrpcTransport",) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..013f5946e819 --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py @@ -0,0 +1,661 @@ +# -*- 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.functions_v2.types import functions + +from .base import DEFAULT_CLIENT_INFO, FunctionServiceTransport +from .grpc import FunctionServiceGrpcTransport + + +class FunctionServiceGrpcAsyncIOTransport(FunctionServiceTransport): + """gRPC AsyncIO backend transport for FunctionService. + + Google Cloud Functions is used to deploy functions that are executed + by Google in response to various events. Data connected with that + event is passed to a function as the input data. + + A **function** is a resource which describes a function that should + be executed and how it is triggered. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudfunctions.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudfunctions.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_function( + self, + ) -> Callable[[functions.GetFunctionRequest], Awaitable[functions.Function]]: + r"""Return a callable for the get function method over gRPC. + + Returns a function with the given name from the + requested project. + + Returns: + Callable[[~.GetFunctionRequest], + Awaitable[~.Function]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_function" not in self._stubs: + self._stubs["get_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GetFunction", + request_serializer=functions.GetFunctionRequest.serialize, + response_deserializer=functions.Function.deserialize, + ) + return self._stubs["get_function"] + + @property + def list_functions( + self, + ) -> Callable[ + [functions.ListFunctionsRequest], Awaitable[functions.ListFunctionsResponse] + ]: + r"""Return a callable for the list functions method over gRPC. + + Returns a list of functions that belong to the + requested project. + + Returns: + Callable[[~.ListFunctionsRequest], + Awaitable[~.ListFunctionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_functions" not in self._stubs: + self._stubs["list_functions"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListFunctions", + request_serializer=functions.ListFunctionsRequest.serialize, + response_deserializer=functions.ListFunctionsResponse.deserialize, + ) + return self._stubs["list_functions"] + + @property + def create_function( + self, + ) -> Callable[ + [functions.CreateFunctionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create function method over gRPC. + + Creates a new function. If a function with the given name + already exists in the specified project, the long running + operation will return ``ALREADY_EXISTS`` error. + + Returns: + Callable[[~.CreateFunctionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_function" not in self._stubs: + self._stubs["create_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/CreateFunction", + request_serializer=functions.CreateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_function"] + + @property + def update_function( + self, + ) -> Callable[ + [functions.UpdateFunctionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update function method over gRPC. + + Updates existing function. + + Returns: + Callable[[~.UpdateFunctionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_function" not in self._stubs: + self._stubs["update_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/UpdateFunction", + request_serializer=functions.UpdateFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_function"] + + @property + def delete_function( + self, + ) -> Callable[ + [functions.DeleteFunctionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete function method over gRPC. + + Deletes a function with the given name from the + specified project. If the given function is used by some + trigger, the trigger will be updated to remove this + function. + + Returns: + Callable[[~.DeleteFunctionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_function" not in self._stubs: + self._stubs["delete_function"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/DeleteFunction", + request_serializer=functions.DeleteFunctionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_function"] + + @property + def generate_upload_url( + self, + ) -> Callable[ + [functions.GenerateUploadUrlRequest], + Awaitable[functions.GenerateUploadUrlResponse], + ]: + r"""Return a callable for the generate upload url method over gRPC. + + Returns a signed URL for uploading a function source code. For + more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls. + Once the function source code upload is complete, the used + signed URL should be provided in CreateFunction or + UpdateFunction request as a reference to the function source + code. + + When uploading source code to the generated signed URL, please + follow these restrictions: + + - Source file type should be a zip file. + - No credentials should be attached - the signed URLs provide + access to the target bucket using internal service identity; + if credentials were attached, the identity from the + credentials would be used, but that identity does not have + permissions to upload files to the URL. + + When making a HTTP PUT request, these two headers need to be + specified: + + - ``content-type: application/zip`` + + And this header SHOULD NOT be specified: + + - ``Authorization: Bearer YOUR_TOKEN`` + + Returns: + Callable[[~.GenerateUploadUrlRequest], + Awaitable[~.GenerateUploadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_upload_url" not in self._stubs: + self._stubs["generate_upload_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateUploadUrl", + request_serializer=functions.GenerateUploadUrlRequest.serialize, + response_deserializer=functions.GenerateUploadUrlResponse.deserialize, + ) + return self._stubs["generate_upload_url"] + + @property + def generate_download_url( + self, + ) -> Callable[ + [functions.GenerateDownloadUrlRequest], + Awaitable[functions.GenerateDownloadUrlResponse], + ]: + r"""Return a callable for the generate download url method over gRPC. + + Returns a signed URL for downloading deployed + function source code. The URL is only valid for a + limited period and should be used within 30 minutes of + generation. + For more information about the signed URL usage see: + https://cloud.google.com/storage/docs/access-control/signed-urls + + Returns: + Callable[[~.GenerateDownloadUrlRequest], + Awaitable[~.GenerateDownloadUrlResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_download_url" not in self._stubs: + self._stubs["generate_download_url"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/GenerateDownloadUrl", + request_serializer=functions.GenerateDownloadUrlRequest.serialize, + response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, + ) + return self._stubs["generate_download_url"] + + @property + def list_runtimes( + self, + ) -> Callable[ + [functions.ListRuntimesRequest], Awaitable[functions.ListRuntimesResponse] + ]: + r"""Return a callable for the list runtimes method over gRPC. + + Returns a list of runtimes that are supported for the + requested project. + + Returns: + Callable[[~.ListRuntimesRequest], + Awaitable[~.ListRuntimesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_runtimes" not in self._stubs: + self._stubs["list_runtimes"] = self.grpc_channel.unary_unary( + "/google.cloud.functions.v2.FunctionService/ListRuntimes", + request_serializer=functions.ListRuntimesRequest.serialize, + response_deserializer=functions.ListRuntimesResponse.deserialize, + ) + return self._stubs["list_runtimes"] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("FunctionServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/types/__init__.py b/packages/google-cloud-functions/google/cloud/functions_v2/types/__init__.py new file mode 100644 index 000000000000..82a10a91e35e --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/types/__init__.py @@ -0,0 +1,74 @@ +# -*- 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 .functions import ( + BuildConfig, + CreateFunctionRequest, + DeleteFunctionRequest, + Environment, + EventFilter, + EventTrigger, + Function, + GenerateDownloadUrlRequest, + GenerateDownloadUrlResponse, + GenerateUploadUrlRequest, + GenerateUploadUrlResponse, + GetFunctionRequest, + ListFunctionsRequest, + ListFunctionsResponse, + ListRuntimesRequest, + ListRuntimesResponse, + OperationMetadata, + RepoSource, + SecretEnvVar, + SecretVolume, + ServiceConfig, + Source, + SourceProvenance, + Stage, + StateMessage, + StorageSource, + UpdateFunctionRequest, +) + +__all__ = ( + "BuildConfig", + "CreateFunctionRequest", + "DeleteFunctionRequest", + "EventFilter", + "EventTrigger", + "Function", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "RepoSource", + "SecretEnvVar", + "SecretVolume", + "ServiceConfig", + "Source", + "SourceProvenance", + "Stage", + "StateMessage", + "StorageSource", + "UpdateFunctionRequest", + "Environment", +) diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/types/functions.py b/packages/google-cloud-functions/google/cloud/functions_v2/types/functions.py new file mode 100644 index 000000000000..04435fb99a0c --- /dev/null +++ b/packages/google-cloud-functions/google/cloud/functions_v2/types/functions.py @@ -0,0 +1,1367 @@ +# -*- 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.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.functions.v2", + manifest={ + "Environment", + "Function", + "StateMessage", + "StorageSource", + "RepoSource", + "Source", + "SourceProvenance", + "BuildConfig", + "ServiceConfig", + "SecretEnvVar", + "SecretVolume", + "EventTrigger", + "EventFilter", + "GetFunctionRequest", + "ListFunctionsRequest", + "ListFunctionsResponse", + "CreateFunctionRequest", + "UpdateFunctionRequest", + "DeleteFunctionRequest", + "GenerateUploadUrlRequest", + "GenerateUploadUrlResponse", + "GenerateDownloadUrlRequest", + "GenerateDownloadUrlResponse", + "ListRuntimesRequest", + "ListRuntimesResponse", + "OperationMetadata", + "Stage", + }, +) + + +class Environment(proto.Enum): + r"""The environment the function is hosted on.""" + ENVIRONMENT_UNSPECIFIED = 0 + GEN_1 = 1 + GEN_2 = 2 + + +class Function(proto.Message): + r"""Describes a Cloud Function that contains user computation + executed in response to an event. It encapsulates function and + trigger configurations. + + Attributes: + name (str): + A user-defined name of the function. Function names must be + unique globally and match pattern + ``projects/*/locations/*/functions/*`` + environment (google.cloud.functions_v2.types.Environment): + Describe whether the function is gen1 or + gen2. + description (str): + User-provided description of a function. + build_config (google.cloud.functions_v2.types.BuildConfig): + Describes the Build step of the function that + builds a container from the given source. + service_config (google.cloud.functions_v2.types.ServiceConfig): + Describes the Service being deployed. + Currently deploys services to Cloud Run (fully + managed). + event_trigger (google.cloud.functions_v2.types.EventTrigger): + An Eventarc trigger managed by Google Cloud + Functions that fires events in response to a + condition in another service. + state (google.cloud.functions_v2.types.Function.State): + Output only. State of the function. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update timestamp of a + Cloud Function. + labels (Mapping[str, str]): + Labels associated with this Cloud Function. + state_messages (Sequence[google.cloud.functions_v2.types.StateMessage]): + Output only. State Messages for this Cloud + Function. + """ + + class State(proto.Enum): + r"""Describes the current state of the function.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + FAILED = 2 + DEPLOYING = 3 + DELETING = 4 + UNKNOWN = 5 + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.ENUM, + number=10, + enum="Environment", + ) + description = proto.Field( + proto.STRING, + number=2, + ) + build_config = proto.Field( + proto.MESSAGE, + number=3, + message="BuildConfig", + ) + service_config = proto.Field( + proto.MESSAGE, + number=4, + message="ServiceConfig", + ) + event_trigger = proto.Field( + proto.MESSAGE, + number=5, + message="EventTrigger", + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + update_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + state_messages = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="StateMessage", + ) + + +class StateMessage(proto.Message): + r"""Informational messages about the state of the Cloud Function + or Operation. + + Attributes: + severity (google.cloud.functions_v2.types.StateMessage.Severity): + Severity of the state message. + type_ (str): + One-word CamelCase type of the state message. + message (str): + The message. + """ + + class Severity(proto.Enum): + r"""Severity of the state message.""" + SEVERITY_UNSPECIFIED = 0 + ERROR = 1 + WARNING = 2 + INFO = 3 + + severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + type_ = proto.Field( + proto.STRING, + number=2, + ) + message = proto.Field( + proto.STRING, + number=3, + ) + + +class StorageSource(proto.Message): + r"""Location of the source in an archive file in Google Cloud + Storage. + + Attributes: + bucket (str): + Google Cloud Storage bucket containing the source (see + `Bucket Name + Requirements `__). + object_ (str): + Google Cloud Storage object containing the source. + + This object must be a gzipped archive file (``.tar.gz``) + containing source to build. + generation (int): + Google Cloud Storage generation for the + object. If the generation is omitted, the latest + generation will be used. + """ + + bucket = proto.Field( + proto.STRING, + number=1, + ) + object_ = proto.Field( + proto.STRING, + number=2, + ) + generation = proto.Field( + proto.INT64, + number=3, + ) + + +class RepoSource(proto.Message): + r"""Location of the source in a Google Cloud Source Repository. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + branch_name (str): + Regex matching branches to build. + The syntax of the regular expressions accepted + is the syntax accepted by RE2 and described at + https://github.com/google/re2/wiki/Syntax + + This field is a member of `oneof`_ ``revision``. + tag_name (str): + Regex matching tags to build. + The syntax of the regular expressions accepted + is the syntax accepted by RE2 and described at + https://github.com/google/re2/wiki/Syntax + + This field is a member of `oneof`_ ``revision``. + commit_sha (str): + Explicit commit SHA to build. + + This field is a member of `oneof`_ ``revision``. + project_id (str): + ID of the project that owns the Cloud Source + Repository. If omitted, the project ID + requesting the build is assumed. + repo_name (str): + Name of the Cloud Source Repository. + dir_ (str): + Directory, relative to the source root, in which to run the + build. + + This must be a relative path. If a step's ``dir`` is + specified and is an absolute path, this value is ignored for + that step's execution. eg. helloworld (no leading slash + allowed) + invert_regex (bool): + Only trigger a build if the revision regex + does NOT match the revision regex. + """ + + branch_name = proto.Field( + proto.STRING, + number=3, + oneof="revision", + ) + tag_name = proto.Field( + proto.STRING, + number=4, + oneof="revision", + ) + commit_sha = proto.Field( + proto.STRING, + number=5, + oneof="revision", + ) + project_id = proto.Field( + proto.STRING, + number=1, + ) + repo_name = proto.Field( + proto.STRING, + number=2, + ) + dir_ = proto.Field( + proto.STRING, + number=6, + ) + invert_regex = proto.Field( + proto.BOOL, + number=7, + ) + + +class Source(proto.Message): + r"""The location of the function source code. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + storage_source (google.cloud.functions_v2.types.StorageSource): + If provided, get the source from this + location in Google Cloud Storage. + + This field is a member of `oneof`_ ``source``. + repo_source (google.cloud.functions_v2.types.RepoSource): + If provided, get the source from this + location in a Cloud Source Repository. + + This field is a member of `oneof`_ ``source``. + """ + + storage_source = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="StorageSource", + ) + repo_source = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="RepoSource", + ) + + +class SourceProvenance(proto.Message): + r"""Provenance of the source. Ways to find the original source, + or verify that some source was used for this build. + + Attributes: + resolved_storage_source (google.cloud.functions_v2.types.StorageSource): + A copy of the build's ``source.storage_source``, if exists, + with any generations resolved. + resolved_repo_source (google.cloud.functions_v2.types.RepoSource): + A copy of the build's ``source.repo_source``, if exists, + with any revisions resolved. + """ + + resolved_storage_source = proto.Field( + proto.MESSAGE, + number=1, + message="StorageSource", + ) + resolved_repo_source = proto.Field( + proto.MESSAGE, + number=2, + message="RepoSource", + ) + + +class BuildConfig(proto.Message): + r"""Describes the Build step of the function that builds a + container from the given source. + + Attributes: + build (str): + Output only. The Cloud Build name of the + latest successful deployment of the function. + runtime (str): + The runtime in which to run the function. Required when + deploying a new function, optional when updating an existing + function. For a complete list of possible choices, see the + ```gcloud`` command + reference `__. + entry_point (str): + The name of the function (as defined in source code) that + will be executed. Defaults to the resource name suffix, if + not specified. For backward compatibility, if function with + given name is not found, then the system will try to use + function named "function". For Node.js this is name of a + function exported by the module specified in + ``source_location``. + source (google.cloud.functions_v2.types.Source): + The location of the function source code. + source_provenance (google.cloud.functions_v2.types.SourceProvenance): + Output only. A permanent fixed identifier for + source. + worker_pool (str): + Name of the Cloud Build Custom Worker Pool that should be + used to build the function. The format of this field is + ``projects/{project}/locations/{region}/workerPools/{workerPool}`` + where {project} and {region} are the project id and region + respectively where the worker pool is defined and + {workerPool} is the short name of the worker pool. + + If the project id is not the same as the function, then the + Cloud Functions Service Agent + (service-@gcf-admin-robot.iam.gserviceaccount.com) + must be granted the role Cloud Build Custom Workers Builder + (roles/cloudbuild.customworkers.builder) in the project. + environment_variables (Mapping[str, str]): + User-provided build-time environment + variables for the function + docker_repository (str): + Optional. User managed repository created in Artifact + Registry optionally with a customer managed encryption key. + This is the repository to which the function docker image + will be pushed after it is built by Cloud Build. If + unspecified, GCF will create and use a repository named + 'gcf-artifacts' for every deployed region. + + It must match the pattern + ``projects/{project}/locations/{location}/repositories/{repository}``. + + Cross-project repositories are not supported. Cross-location + repositories are not supported. Repository format must be + 'DOCKER'. + """ + + build = proto.Field( + proto.STRING, + number=1, + ) + runtime = proto.Field( + proto.STRING, + number=2, + ) + entry_point = proto.Field( + proto.STRING, + number=3, + ) + source = proto.Field( + proto.MESSAGE, + number=4, + message="Source", + ) + source_provenance = proto.Field( + proto.MESSAGE, + number=8, + message="SourceProvenance", + ) + worker_pool = proto.Field( + proto.STRING, + number=5, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + docker_repository = proto.Field( + proto.STRING, + number=7, + ) + + +class ServiceConfig(proto.Message): + r"""Describes the Service being deployed. + Currently Supported : Cloud Run (fully managed). + + Attributes: + service (str): + Output only. Name of the service associated with a Function. + The format of this field is + ``projects/{project}/locations/{region}/services/{service}`` + timeout_seconds (int): + The function execution timeout. Execution is + considered failed and can be terminated if the + function is not completed at the end of the + timeout period. Defaults to 60 seconds. + available_memory (str): + The amount of memory available for a + function. Defaults to 256M. Supported units are + k, M, G, Mi, Gi. If no unit is supplied the + value is interpreted as bytes. + See + https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go + a full description. + environment_variables (Mapping[str, str]): + Environment variables that shall be available + during function execution. + max_instance_count (int): + The limit on the maximum number of function instances that + may coexist at a given time. + + In some cases, such as rapid traffic surges, Cloud Functions + may, for a short period of time, create more instances than + the specified max instances limit. If your function cannot + tolerate this temporary behavior, you may want to factor in + a safety margin and set a lower max instances value than + your function can tolerate. + + See the `Max + Instances `__ + Guide for more details. + min_instance_count (int): + The limit on the minimum number of function + instances that may coexist at a given time. + + Function instances are kept in idle state for a + short period after they finished executing the + request to reduce cold start time for subsequent + requests. Setting a minimum instance count will + ensure that the given number of instances are + kept running in idle state always. This can help + with cold start times when jump in incoming + request count occurs after the idle instance + would have been stopped in the default case. + vpc_connector (str): + The Serverless VPC Access connector that this cloud function + can connect to. The format of this field is + ``projects/*/locations/*/connectors/*``. + vpc_connector_egress_settings (google.cloud.functions_v2.types.ServiceConfig.VpcConnectorEgressSettings): + The egress settings for the connector, + controlling what traffic is diverted through it. + ingress_settings (google.cloud.functions_v2.types.ServiceConfig.IngressSettings): + The ingress settings for the function, + controlling what traffic can reach it. + uri (str): + Output only. URI of the Service deployed. + service_account_email (str): + The email of the service's service account. If empty, + defaults to + ``{project_number}-compute@developer.gserviceaccount.com``. + all_traffic_on_latest_revision (bool): + Whether 100% of traffic is routed to the + latest revision. On CreateFunction and + UpdateFunction, when set to true, the revision + being deployed will serve 100% of traffic, + ignoring any traffic split settings, if any. On + GetFunction, true will be returned if the latest + revision is serving 100% of traffic. + secret_environment_variables (Sequence[google.cloud.functions_v2.types.SecretEnvVar]): + Secret environment variables configuration. + secret_volumes (Sequence[google.cloud.functions_v2.types.SecretVolume]): + Secret volumes configuration. + revision (str): + Output only. The name of service revision. + """ + + class VpcConnectorEgressSettings(proto.Enum): + r"""Available egress settings. + + This controls what traffic is diverted through the VPC Access + Connector resource. By default PRIVATE_RANGES_ONLY will be used. + """ + VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED = 0 + PRIVATE_RANGES_ONLY = 1 + ALL_TRAFFIC = 2 + + class IngressSettings(proto.Enum): + r"""Available ingress settings. + + This controls what traffic can reach the function. + + If unspecified, ALLOW_ALL will be used. + """ + INGRESS_SETTINGS_UNSPECIFIED = 0 + ALLOW_ALL = 1 + ALLOW_INTERNAL_ONLY = 2 + ALLOW_INTERNAL_AND_GCLB = 3 + + service = proto.Field( + proto.STRING, + number=1, + ) + timeout_seconds = proto.Field( + proto.INT32, + number=2, + ) + available_memory = proto.Field( + proto.STRING, + number=13, + ) + environment_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + max_instance_count = proto.Field( + proto.INT32, + number=5, + ) + min_instance_count = proto.Field( + proto.INT32, + number=12, + ) + vpc_connector = proto.Field( + proto.STRING, + number=6, + ) + vpc_connector_egress_settings = proto.Field( + proto.ENUM, + number=7, + enum=VpcConnectorEgressSettings, + ) + ingress_settings = proto.Field( + proto.ENUM, + number=8, + enum=IngressSettings, + ) + uri = proto.Field( + proto.STRING, + number=9, + ) + service_account_email = proto.Field( + proto.STRING, + number=10, + ) + all_traffic_on_latest_revision = proto.Field( + proto.BOOL, + number=16, + ) + secret_environment_variables = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="SecretEnvVar", + ) + secret_volumes = proto.RepeatedField( + proto.MESSAGE, + number=19, + message="SecretVolume", + ) + revision = proto.Field( + proto.STRING, + number=18, + ) + + +class SecretEnvVar(proto.Message): + r"""Configuration for a secret environment variable. It has the + information necessary to fetch the secret value from secret + manager and expose it as an environment variable. + + Attributes: + key (str): + Name of the environment variable. + project_id (str): + Project identifier (preferably project number + but can also be the project ID) of the project + that contains the secret. If not set, it is + assumed that the secret is in the same project + as the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + version (str): + Version of the secret (version number or the + string 'latest'). It is recommended to use a + numeric version for secret environment variables + as any updates to the secret value is not + reflected until new instances start. + """ + + key = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + version = proto.Field( + proto.STRING, + number=4, + ) + + +class SecretVolume(proto.Message): + r"""Configuration for a secret volume. It has the information + necessary to fetch the secret value from secret manager and make + it available as files mounted at the requested paths within the + application container. + + Attributes: + mount_path (str): + The path within the container to mount the secret volume. + For example, setting the mount_path as ``/etc/secrets`` + would mount the secret value files under the + ``/etc/secrets`` directory. This directory will also be + completely shadowed and unavailable to mount any other + secrets. Recommended mount path: /etc/secrets + project_id (str): + Project identifier (preferably project number + but can also be the project ID) of the project + that contains the secret. If not set, it is + assumed that the secret is in the same project + as the function. + secret (str): + Name of the secret in secret manager (not the + full resource name). + versions (Sequence[google.cloud.functions_v2.types.SecretVolume.SecretVersion]): + List of secret versions to mount for this secret. If empty, + the ``latest`` version of the secret will be made available + in a file named after the secret under the mount point. + """ + + class SecretVersion(proto.Message): + r"""Configuration for a single version. + + Attributes: + version (str): + Version of the secret (version number or the string + 'latest'). It is preferable to use ``latest`` version with + secret volumes as secret value changes are reflected + immediately. + path (str): + Relative path of the file under the mount path where the + secret value for this version will be fetched and made + available. For example, setting the mount_path as + '/etc/secrets' and path as ``secret_foo`` would mount the + secret value file at ``/etc/secrets/secret_foo``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + + mount_path = proto.Field( + proto.STRING, + number=1, + ) + project_id = proto.Field( + proto.STRING, + number=2, + ) + secret = proto.Field( + proto.STRING, + number=3, + ) + versions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SecretVersion, + ) + + +class EventTrigger(proto.Message): + r"""Describes EventTrigger, used to request events to be sent + from another service. + + Attributes: + trigger (str): + Output only. The resource name of the Eventarc trigger. The + format of this field is + ``projects/{project}/locations/{region}/triggers/{trigger}``. + trigger_region (str): + The region that the trigger will be in. The + trigger will only receive events originating in + this region. It can be the same region as the + function, a different region or multi-region, or + the global region. If not provided, defaults to + the same region as the function. + event_type (str): + Required. The type of event to observe. For example: + ``google.cloud.audit.log.v1.written`` or + ``google.cloud.pubsub.topic.v1.messagePublished``. + event_filters (Sequence[google.cloud.functions_v2.types.EventFilter]): + Criteria used to filter events. + pubsub_topic (str): + Optional. The name of a Pub/Sub topic in the same project + that will be used as the transport topic for the event + delivery. Format: ``projects/{project}/topics/{topic}``. + + This is only valid for events of type + ``google.cloud.pubsub.topic.v1.messagePublished``. The topic + provided here will not be deleted at function deletion. + service_account_email (str): + Optional. The email of the trigger's service account. The + service account must have permission to invoke Cloud Run + services, the permission is ``run.routes.invoke``. If empty, + defaults to the Compute Engine default service account: + ``{project_number}-compute@developer.gserviceaccount.com``. + retry_policy (google.cloud.functions_v2.types.EventTrigger.RetryPolicy): + Optional. If unset, then defaults to ignoring + failures (i.e. not retrying them). + channel (str): + Optional. The name of the channel associated with the + trigger in + ``projects/{project}/locations/{location}/channels/{channel}`` + format. You must provide a channel to receive events from + Eventarc SaaS partners. + """ + + class RetryPolicy(proto.Enum): + r"""Describes the retry policy in case of function's execution + failure. Retried execution is charged as any other execution. + """ + RETRY_POLICY_UNSPECIFIED = 0 + RETRY_POLICY_DO_NOT_RETRY = 1 + RETRY_POLICY_RETRY = 2 + + trigger = proto.Field( + proto.STRING, + number=1, + ) + trigger_region = proto.Field( + proto.STRING, + number=2, + ) + event_type = proto.Field( + proto.STRING, + number=3, + ) + event_filters = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="EventFilter", + ) + pubsub_topic = proto.Field( + proto.STRING, + number=5, + ) + service_account_email = proto.Field( + proto.STRING, + number=6, + ) + retry_policy = proto.Field( + proto.ENUM, + number=7, + enum=RetryPolicy, + ) + channel = proto.Field( + proto.STRING, + number=8, + ) + + +class EventFilter(proto.Message): + r"""Filters events based on exact matches on the CloudEvents + attributes. + + Attributes: + attribute (str): + Required. The name of a CloudEvents + attribute. + value (str): + Required. The value for the attribute. + operator (str): + Optional. The operator used for matching the events with the + value of the filter. If not specified, only events that have + an exact key-value pair specified in the filter are matched. + The only allowed value is ``match-path-pattern``. + """ + + attribute = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.STRING, + number=2, + ) + operator = proto.Field( + proto.STRING, + number=3, + ) + + +class GetFunctionRequest(proto.Message): + r"""Request for the ``GetFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + details should be obtained. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFunctionsRequest(proto.Message): + r"""Request for the ``ListFunctions`` method. + + Attributes: + parent (str): + Required. The project and location from which the function + should be listed, specified in the format + ``projects/*/locations/*`` If you want to list functions in + all locations, use "-" in place of a location. When listing + functions in all locations, if one or more location(s) are + unreachable, the response will contain functions from all + reachable locations along with the names of any unreachable + locations. + page_size (int): + Maximum number of functions to return per + call. + page_token (str): + The value returned by the last ``ListFunctionsResponse``; + indicates that this is a continuation of a prior + ``ListFunctions`` call, and that the system should return + the next page of data. + filter (str): + The filter for Functions that match the + filter expression, following the syntax outlined + in https://google.aip.dev/160. + order_by (str): + The sorting order of the resources returned. + Value should be a comma separated list of + fields. The default sorting oder is ascending. + See https://google.aip.dev/132#ordering. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListFunctionsResponse(proto.Message): + r"""Response for the ``ListFunctions`` method. + + Attributes: + functions (Sequence[google.cloud.functions_v2.types.Function]): + The functions that match the request. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (Sequence[str]): + Locations that could not be reached. The + response does not include any functions from + these locations. + """ + + @property + def raw_page(self): + return self + + functions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Function", + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + unreachable = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateFunctionRequest(proto.Message): + r"""Request for the ``CreateFunction`` method. + + Attributes: + parent (str): + Required. The project and location in which the function + should be created, specified in the format + ``projects/*/locations/*`` + function (google.cloud.functions_v2.types.Function): + Required. Function to be created. + function_id (str): + The ID to use for the function, which will become the final + component of the function's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + function = proto.Field( + proto.MESSAGE, + number=2, + message="Function", + ) + function_id = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateFunctionRequest(proto.Message): + r"""Request for the ``UpdateFunction`` method. + + Attributes: + function (google.cloud.functions_v2.types.Function): + Required. New version of the function. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If no field mask is provided, all provided + fields in the request will be updated. + """ + + function = proto.Field( + proto.MESSAGE, + number=1, + message="Function", + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteFunctionRequest(proto.Message): + r"""Request for the ``DeleteFunction`` method. + + Attributes: + name (str): + Required. The name of the function which + should be deleted. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateUploadUrlRequest(proto.Message): + r"""Request of ``GenerateSourceUploadUrl`` method. + + Attributes: + parent (str): + Required. The project and location in which the Google Cloud + Storage signed URL should be generated, specified in the + format ``projects/*/locations/*``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateUploadUrlResponse(proto.Message): + r"""Response of ``GenerateSourceUploadUrl`` method. + + Attributes: + upload_url (str): + The generated Google Cloud Storage signed URL + that should be used for a function source code + upload. The uploaded file should be a zip + archive which contains a function. + storage_source (google.cloud.functions_v2.types.StorageSource): + The location of the source code in the upload bucket. + + Once the archive is uploaded using the ``upload_url`` use + this field to set the + ``function.build_config.source.storage_source`` during + CreateFunction and UpdateFunction. + + Generation defaults to 0, as Cloud Storage provides a new + generation only upon uploading a new object or version of an + object. + """ + + upload_url = proto.Field( + proto.STRING, + number=1, + ) + storage_source = proto.Field( + proto.MESSAGE, + number=2, + message="StorageSource", + ) + + +class GenerateDownloadUrlRequest(proto.Message): + r"""Request of ``GenerateDownloadUrl`` method. + + Attributes: + name (str): + Required. The name of function for which + source code Google Cloud Storage signed URL + should be generated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateDownloadUrlResponse(proto.Message): + r"""Response of ``GenerateDownloadUrl`` method. + + Attributes: + download_url (str): + The generated Google Cloud Storage signed URL + that should be used for function source code + download. + """ + + download_url = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRuntimesRequest(proto.Message): + r"""Request for the ``ListRuntimes`` method. + + Attributes: + parent (str): + Required. The project and location from which the runtimes + should be listed, specified in the format + ``projects/*/locations/*`` + filter (str): + The filter for Runtimes that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + + +class ListRuntimesResponse(proto.Message): + r"""Response for the ``ListRuntimes`` method. + + Attributes: + runtimes (Sequence[google.cloud.functions_v2.types.ListRuntimesResponse.Runtime]): + The runtimes that match the request. + """ + + class RuntimeStage(proto.Enum): + r"""The various stages that a runtime can be in.""" + RUNTIME_STAGE_UNSPECIFIED = 0 + DEVELOPMENT = 1 + ALPHA = 2 + BETA = 3 + GA = 4 + DEPRECATED = 5 + DECOMMISSIONED = 6 + + class Runtime(proto.Message): + r"""Describes a runtime and any special information (e.g., + deprecation status) related to it. + + Attributes: + name (str): + The name of the runtime, e.g., 'go113', + 'nodejs12', etc. + display_name (str): + The user facing name, eg 'Go 1.13', 'Node.js + 12', etc. + stage (google.cloud.functions_v2.types.ListRuntimesResponse.RuntimeStage): + The stage of life this runtime is in, e.g., + BETA, GA, etc. + warnings (Sequence[str]): + Warning messages, e.g., a deprecation + warning. + environment (google.cloud.functions_v2.types.Environment): + The environment for the runtime. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=5, + ) + stage = proto.Field( + proto.ENUM, + number=2, + enum="ListRuntimesResponse.RuntimeStage", + ) + warnings = proto.RepeatedField( + proto.STRING, + number=3, + ) + environment = proto.Field( + proto.ENUM, + number=4, + enum="Environment", + ) + + runtimes = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Runtime, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation finished running. + target (str): + Server-defined resource path for the target + of the operation. + verb (str): + Name of the verb executed by the operation. + status_detail (str): + Human-readable status of the operation, if + any. + cancel_requested (bool): + Identifies whether the user has requested cancellation of + the operation. Operations that have successfully been + cancelled have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + API version used to start the operation. + request_resource (google.protobuf.any_pb2.Any): + The original request that started the + operation. + stages (Sequence[google.cloud.functions_v2.types.Stage]): + Mechanism for reporting in-progress stages + """ + + create_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target = proto.Field( + proto.STRING, + number=3, + ) + verb = proto.Field( + proto.STRING, + number=4, + ) + status_detail = proto.Field( + proto.STRING, + number=5, + ) + cancel_requested = proto.Field( + proto.BOOL, + number=6, + ) + api_version = proto.Field( + proto.STRING, + number=7, + ) + request_resource = proto.Field( + proto.MESSAGE, + number=8, + message=any_pb2.Any, + ) + stages = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="Stage", + ) + + +class Stage(proto.Message): + r"""Each Stage of the deployment process + + Attributes: + name (google.cloud.functions_v2.types.Stage.Name): + Name of the Stage. This will be unique for + each Stage. + message (str): + Message describing the Stage + state (google.cloud.functions_v2.types.Stage.State): + Current state of the Stage + resource (str): + Resource of the Stage + resource_uri (str): + Link to the current Stage resource + state_messages (Sequence[google.cloud.functions_v2.types.StateMessage]): + State messages from the current Stage. + """ + + class Name(proto.Enum): + r"""Possible names for a Stage""" + NAME_UNSPECIFIED = 0 + ARTIFACT_REGISTRY = 1 + BUILD = 2 + SERVICE = 3 + TRIGGER = 4 + SERVICE_ROLLBACK = 5 + TRIGGER_ROLLBACK = 6 + + class State(proto.Enum): + r"""Possible states for a Stage""" + STATE_UNSPECIFIED = 0 + NOT_STARTED = 1 + IN_PROGRESS = 2 + COMPLETE = 3 + + name = proto.Field( + proto.ENUM, + number=1, + enum=Name, + ) + message = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + resource = proto.Field( + proto.STRING, + number=4, + ) + resource_uri = proto.Field( + proto.STRING, + number=5, + ) + state_messages = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="StateMessage", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-functions/noxfile.py b/packages/google-cloud-functions/noxfile.py index 94b2f9c20760..94504ea66b69 100644 --- a/packages/google-cloud-functions/noxfile.py +++ b/packages/google-cloud-functions/noxfile.py @@ -266,7 +266,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") + session.run("coverage", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") diff --git a/packages/google-cloud-functions/owlbot.py b/packages/google-cloud-functions/owlbot.py new file mode 100644 index 000000000000..3185247475e5 --- /dev/null +++ b/packages/google-cloud-functions/owlbot.py @@ -0,0 +1,75 @@ +# 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 pathlib import Path + +import synthtool as s +import synthtool.gcp as gcp +from synthtool.languages import python + +# ---------------------------------------------------------------------------- +# Copy the generated client from the owl-bot staging directory +# ---------------------------------------------------------------------------- + +default_version = "v1" + +for library in s.get_staging_dirs(default_version): + # work around issues with docstrings + s.replace( + library / "google/cloud/**/*.py", + """resource. + \*\*JSON Example\*\* + ::""", + """resource. JSON Example. + + .. code-block:: python\n""", + ) + + s.replace( + library / "google/cloud/**/*.py", + """\*\*YAML Example\*\* + ::""", + """\n **YAML Example** + + ::\n""", + ) + + s.replace(library / "google/cloud/**/*.py", + """ For a description of IAM and its features, see the `IAM + developer's""", + """\n For a description of IAM and its features, see the `IAM + developer's""" + ) + s.move(library, excludes=["setup.py"]) + +s.remove_staging_dirs() + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- + +templated_files = gcp.CommonTemplates().py_library( + cov_level=99, + microgenerator=True, + versions=gcp.common.detect_versions(path="./google", default_first=True), +) +s.move(templated_files, excludes=[".coveragerc"]) # the microgenerator has a good coveragerc file + +python.configure_previous_major_version_branches() + +python.py_samples(skip_readmes=True) + +# run format nox session for all directories which have a noxfile +for noxfile in Path(".").glob("**/noxfile.py"): + s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False) diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py new file mode 100644 index 000000000000..b0a73a3c3e9f --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py @@ -0,0 +1,49 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_CreateFunction_async] +from google.cloud import functions_v2 + + +async def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_CreateFunction_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py new file mode 100644 index 000000000000..5f0ffb7b5114 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py @@ -0,0 +1,49 @@ +# -*- 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 CreateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_CreateFunction_sync] +from google.cloud import functions_v2 + + +def sample_create_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.CreateFunctionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_CreateFunction_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py new file mode 100644 index 000000000000..75bd16cfb523 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py @@ -0,0 +1,49 @@ +# -*- 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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_DeleteFunction_async] +from google.cloud import functions_v2 + + +async def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_DeleteFunction_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py new file mode 100644 index 000000000000..5ecc4f6e70e6 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py @@ -0,0 +1,49 @@ +# -*- 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 DeleteFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_DeleteFunction_sync] +from google.cloud import functions_v2 + + +def sample_delete_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.DeleteFunctionRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_DeleteFunction_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py new file mode 100644 index 000000000000..de16eda13e75 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py @@ -0,0 +1,45 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_async] +from google.cloud import functions_v2 + + +async def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py new file mode 100644 index 000000000000..c00c0c4f62ab --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py @@ -0,0 +1,45 @@ +# -*- 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 GenerateDownloadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_sync] +from google.cloud import functions_v2 + + +def sample_generate_download_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateDownloadUrlRequest( + name="name_value", + ) + + # Make the request + response = client.generate_download_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py new file mode 100644 index 000000000000..c66940c629e6 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py @@ -0,0 +1,45 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_async] +from google.cloud import functions_v2 + + +async def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py new file mode 100644 index 000000000000..f895b860908e --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py @@ -0,0 +1,45 @@ +# -*- 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 GenerateUploadUrl +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_sync] +from google.cloud import functions_v2 + + +def sample_generate_upload_url(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GenerateUploadUrlRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_upload_url(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py new file mode 100644 index 000000000000..43d5dfb36b55 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py @@ -0,0 +1,45 @@ +# -*- 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 GetFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GetFunction_async] +from google.cloud import functions_v2 + + +async def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GetFunction_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py new file mode 100644 index 000000000000..8bb3cfa9935f --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py @@ -0,0 +1,45 @@ +# -*- 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 GetFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_GetFunction_sync] +from google.cloud import functions_v2 + + +def sample_get_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.GetFunctionRequest( + name="name_value", + ) + + # Make the request + response = client.get_function(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_GetFunction_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py new file mode 100644 index 000000000000..50b0e79d3380 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py @@ -0,0 +1,46 @@ +# -*- 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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListFunctions_async] +from google.cloud import functions_v2 + + +async def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListFunctions_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py new file mode 100644 index 000000000000..33ae5c5889a4 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py @@ -0,0 +1,46 @@ +# -*- 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 ListFunctions +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListFunctions_sync] +from google.cloud import functions_v2 + + +def sample_list_functions(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListFunctionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_functions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListFunctions_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py new file mode 100644 index 000000000000..410226fba24b --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py @@ -0,0 +1,45 @@ +# -*- 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 ListRuntimes +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListRuntimes_async] +from google.cloud import functions_v2 + + +async def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_runtimes(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListRuntimes_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py new file mode 100644 index 000000000000..b942e09d74d6 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py @@ -0,0 +1,45 @@ +# -*- 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 ListRuntimes +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_ListRuntimes_sync] +from google.cloud import functions_v2 + + +def sample_list_runtimes(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.ListRuntimesRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_runtimes(request=request) + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_ListRuntimes_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py new file mode 100644 index 000000000000..42fc5165d4bd --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py @@ -0,0 +1,48 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_UpdateFunction_async] +from google.cloud import functions_v2 + + +async def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceAsyncClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_UpdateFunction_async] diff --git a/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py new file mode 100644 index 000000000000..dfb79691e229 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py @@ -0,0 +1,48 @@ +# -*- 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 UpdateFunction +# 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-functions + + +# [START cloudfunctions_v2_generated_FunctionService_UpdateFunction_sync] +from google.cloud import functions_v2 + + +def sample_update_function(): + # Create a client + client = functions_v2.FunctionServiceClient() + + # Initialize request argument(s) + request = functions_v2.UpdateFunctionRequest( + ) + + # Make the request + operation = client.update_function(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudfunctions_v2_generated_FunctionService_UpdateFunction_sync] diff --git a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_functions_v2.json b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_functions_v2.json new file mode 100644 index 000000000000..7b0dbb7b4489 --- /dev/null +++ b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_functions_v2.json @@ -0,0 +1,1310 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.functions.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-functions" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.create_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.CreateFunctionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "function_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_async.AsyncOperation", + "shortName": "create_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v2_generated_function_service_create_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_CreateFunction_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_create_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.create_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.CreateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "CreateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.CreateFunctionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "function_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_function" + }, + "description": "Sample for CreateFunction", + "file": "cloudfunctions_v2_generated_function_service_create_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_CreateFunction_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_create_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.DeleteFunctionRequest" + }, + { + "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_async.AsyncOperation", + "shortName": "delete_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v2_generated_function_service_delete_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_DeleteFunction_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_delete_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.delete_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.DeleteFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "DeleteFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.DeleteFunctionRequest" + }, + { + "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_function" + }, + "description": "Sample for DeleteFunction", + "file": "cloudfunctions_v2_generated_function_service_delete_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_DeleteFunction_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_delete_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_download_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_download_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.generate_download_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateDownloadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateDownloadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateDownloadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateDownloadUrlResponse", + "shortName": "generate_download_url" + }, + "description": "Sample for GenerateDownloadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_download_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateDownloadUrl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_download_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_upload_url_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_upload_url_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.generate_upload_url", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GenerateUploadUrl", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GenerateUploadUrl" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GenerateUploadUrlRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.functions_v2.types.GenerateUploadUrlResponse", + "shortName": "generate_upload_url" + }, + "description": "Sample for GenerateUploadUrl", + "file": "cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GenerateUploadUrl_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.get_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GetFunctionRequest" + }, + { + "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.functions_v2.types.Function", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v2_generated_function_service_get_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GetFunction_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_get_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.get_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.GetFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "GetFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.GetFunctionRequest" + }, + { + "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.functions_v2.types.Function", + "shortName": "get_function" + }, + "description": "Sample for GetFunction", + "file": "cloudfunctions_v2_generated_function_service_get_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_GetFunction_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_get_function_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListFunctionsRequest" + }, + { + "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.functions_v2.services.function_service.pagers.ListFunctionsAsyncPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v2_generated_function_service_list_functions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListFunctions_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_functions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.list_functions", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListFunctions", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListFunctions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListFunctionsRequest" + }, + { + "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.functions_v2.services.function_service.pagers.ListFunctionsPager", + "shortName": "list_functions" + }, + "description": "Sample for ListFunctions", + "file": "cloudfunctions_v2_generated_function_service_list_functions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListFunctions_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_functions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.list_runtimes", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListRuntimes", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListRuntimes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListRuntimesRequest" + }, + { + "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.functions_v2.types.ListRuntimesResponse", + "shortName": "list_runtimes" + }, + "description": "Sample for ListRuntimes", + "file": "cloudfunctions_v2_generated_function_service_list_runtimes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListRuntimes_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_runtimes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.list_runtimes", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.ListRuntimes", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "ListRuntimes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.ListRuntimesRequest" + }, + { + "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.functions_v2.types.ListRuntimesResponse", + "shortName": "list_runtimes" + }, + "description": "Sample for ListRuntimes", + "file": "cloudfunctions_v2_generated_function_service_list_runtimes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_ListRuntimes_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_list_runtimes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient", + "shortName": "FunctionServiceAsyncClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceAsyncClient.update_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v2_generated_function_service_update_function_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_UpdateFunction_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_update_function_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.functions_v2.FunctionServiceClient", + "shortName": "FunctionServiceClient" + }, + "fullName": "google.cloud.functions_v2.FunctionServiceClient.update_function", + "method": { + "fullName": "google.cloud.functions.v2.FunctionService.UpdateFunction", + "service": { + "fullName": "google.cloud.functions.v2.FunctionService", + "shortName": "FunctionService" + }, + "shortName": "UpdateFunction" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.functions_v2.types.UpdateFunctionRequest" + }, + { + "name": "function", + "type": "google.cloud.functions_v2.types.Function" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_function" + }, + "description": "Sample for UpdateFunction", + "file": "cloudfunctions_v2_generated_function_service_update_function_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudfunctions_v2_generated_FunctionService_UpdateFunction_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudfunctions_v2_generated_function_service_update_function_sync.py" + } + ] +} diff --git a/packages/google-cloud-functions/scripts/fixup_functions_v2_keywords.py b/packages/google-cloud-functions/scripts/fixup_functions_v2_keywords.py new file mode 100644 index 000000000000..e95731994da8 --- /dev/null +++ b/packages/google-cloud-functions/scripts/fixup_functions_v2_keywords.py @@ -0,0 +1,183 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class functionsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_function': ('parent', 'function', 'function_id', ), + 'delete_function': ('name', ), + 'generate_download_url': ('name', ), + 'generate_upload_url': ('parent', ), + 'get_function': ('name', ), + 'list_functions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_runtimes': ('parent', 'filter', ), + 'update_function': ('function', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=functionsCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the functions client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-functions/setup.py b/packages/google-cloud-functions/setup.py index 5d91e1e48446..99f6b7fef887 100644 --- a/packages/google-cloud-functions/setup.py +++ b/packages/google-cloud-functions/setup.py @@ -46,10 +46,7 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - # NOTE: Maintainers, please do not require google-api-core>=2.x.x - # Until this issue is closed - # https://github.com/googleapis/google-cloud-python/issues/10566 - "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "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.*", "proto-plus >= 1.15.0, <2.0.0dev", "protobuf >= 3.19.0, <4.0.0dev", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-functions/testing/constraints-3.6.txt b/packages/google-cloud-functions/testing/constraints-3.6.txt deleted file mode 100644 index 60b7a7a56ec6..000000000000 --- a/packages/google-cloud-functions/testing/constraints-3.6.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List *all* library dependencies and extras in this file. -# Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.31.5 -proto-plus==1.15.0 -grpc-google-iam-v1==0.12.4 -protobuf==3.19.0 diff --git a/packages/google-cloud-functions/testing/constraints-3.7.txt b/packages/google-cloud-functions/testing/constraints-3.7.txt index 60b7a7a56ec6..f9ec620c7f78 100644 --- a/packages/google-cloud-functions/testing/constraints-3.7.txt +++ b/packages/google-cloud-functions/testing/constraints-3.7.txt @@ -5,7 +5,7 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.31.5 +google-api-core==1.32.0 proto-plus==1.15.0 grpc-google-iam-v1==0.12.4 protobuf==3.19.0 diff --git a/packages/google-cloud-functions/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/packages/google-cloud-functions/tests/unit/gapic/functions_v1/test_cloud_functions_service.py index 7db328fadd4b..6606e10a4f01 100644 --- a/packages/google-cloud-functions/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ b/packages/google-cloud-functions/tests/unit/gapic/functions_v1/test_cloud_functions_service.py @@ -249,6 +249,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -266,6 +267,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -283,6 +285,7 @@ def test_cloud_functions_service_client_client_options( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -312,6 +315,25 @@ def test_cloud_functions_service_client_client_options( quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", ) @@ -389,6 +411,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -423,6 +446,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -445,6 +469,7 @@ def test_cloud_functions_service_client_mtls_env_auto( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -563,6 +588,7 @@ def test_cloud_functions_service_client_client_options_scopes( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -601,6 +627,7 @@ def test_cloud_functions_service_client_client_options_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -621,6 +648,7 @@ def test_cloud_functions_service_client_client_options_from_dict(): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) @@ -659,6 +687,7 @@ def test_cloud_functions_service_client_create_channel_credentials_file( quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) # test that the credentials from file are saved and used as the credentials. @@ -3373,6 +3402,28 @@ def test_cloud_functions_service_transport_auth_adc(transport_class): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudFunctionsServiceGrpcTransport, + transports.CloudFunctionsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_functions_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + @pytest.mark.parametrize( "transport_class,grpc_helpers", [ @@ -3943,4 +3994,5 @@ def test_api_key_credentials(client_class, transport_class): quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, + api_audience=None, ) diff --git a/packages/google-cloud-functions/tests/unit/gapic/functions_v2/__init__.py b/packages/google-cloud-functions/tests/unit/gapic/functions_v2/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/packages/google-cloud-functions/tests/unit/gapic/functions_v2/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/packages/google-cloud-functions/tests/unit/gapic/functions_v2/test_function_service.py b/packages/google-cloud-functions/tests/unit/gapic/functions_v2/test_function_service.py new file mode 100644 index 000000000000..a28e59d50fc4 --- /dev/null +++ b/packages/google-cloud-functions/tests/unit/gapic/functions_v2/test_function_service.py @@ -0,0 +1,4544 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock +except ImportError: + import mock + +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.functions_v2.services.function_service import ( + FunctionServiceAsyncClient, + FunctionServiceClient, + pagers, + transports, +) +from google.cloud.functions_v2.types import functions + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FunctionServiceClient._get_default_mtls_endpoint(None) is None + assert ( + FunctionServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FunctionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_function_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ("cloudfunctions.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.FunctionServiceGrpcTransport, "grpc"), + (transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_function_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FunctionServiceClient, "grpc"), + (FunctionServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_function_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ("cloudfunctions.googleapis.com:443") + + +def test_function_service_client_get_transport_class(): + transport = FunctionServiceClient.get_transport_class() + available_transports = [ + transports.FunctionServiceGrpcTransport, + ] + assert transport in available_transports + + transport = FunctionServiceClient.get_transport_class("grpc") + assert transport == transports.FunctionServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) +def test_function_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FunctionServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FunctionServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + "true", + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + "false", + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_function_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [FunctionServiceClient, FunctionServiceAsyncClient] +) +@mock.patch.object( + FunctionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceClient), +) +@mock.patch.object( + FunctionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FunctionServiceAsyncClient), +) +def test_function_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_function_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_function_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_function_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = FunctionServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + FunctionServiceClient, + transports.FunctionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FunctionServiceAsyncClient, + transports.FunctionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_function_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudfunctions.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + functions.GetFunctionRequest, + dict, + ], +) +def test_get_function(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function( + name="name_value", + environment=functions.Environment.GEN_1, + description="description_value", + state=functions.Function.State.ACTIVE, + ) + response = client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.Function) + assert response.name == "name_value" + assert response.environment == functions.Environment.GEN_1 + assert response.description == "description_value" + assert response.state == functions.Function.State.ACTIVE + + +def test_get_function_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + client.get_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + +@pytest.mark.asyncio +async def test_get_function_async( + transport: str = "grpc_asyncio", request_type=functions.GetFunctionRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.Function( + name="name_value", + environment=functions.Environment.GEN_1, + description="description_value", + state=functions.Function.State.ACTIVE, + ) + ) + response = await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GetFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.Function) + assert response.name == "name_value" + assert response.environment == functions.Environment.GEN_1 + assert response.description == "description_value" + assert response.state == functions.Function.State.ACTIVE + + +@pytest.mark.asyncio +async def test_get_function_async_from_dict(): + await test_get_function_async(request_type=dict) + + +def test_get_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + call.return_value = functions.Function() + client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GetFunctionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.Function()) + await client.get_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_function( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_function_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_function( + functions.GetFunctionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.Function() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.Function()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_function( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_function( + functions.GetFunctionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + functions.ListFunctionsRequest, + dict, + ], +) +def test_list_functions(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_functions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + client.list_functions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + +@pytest.mark.asyncio +async def test_list_functions_async( + transport: str = "grpc_asyncio", request_type=functions.ListFunctionsRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListFunctionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFunctionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_functions_async_from_dict(): + await test_list_functions_async(request_type=dict) + + +def test_list_functions_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + call.return_value = functions.ListFunctionsResponse() + client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_functions_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListFunctionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse() + ) + await client.list_functions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_functions_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_functions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_functions_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_functions( + functions.ListFunctionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_functions_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListFunctionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListFunctionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_functions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_functions_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_functions( + functions.ListFunctionsRequest(), + parent="parent_value", + ) + + +def test_list_functions_pager(transport_name: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token="abc", + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token="def", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token="ghi", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_functions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, functions.Function) for i in results) + + +def test_list_functions_pages(transport_name: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_functions), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token="abc", + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token="def", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token="ghi", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + pages = list(client.list_functions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_functions_async_pager(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token="abc", + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token="def", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token="ghi", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_functions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, functions.Function) for i in responses) + + +@pytest.mark.asyncio +async def test_list_functions_async_pages(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_functions), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + functions.Function(), + ], + next_page_token="abc", + ), + functions.ListFunctionsResponse( + functions=[], + next_page_token="def", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + ], + next_page_token="ghi", + ), + functions.ListFunctionsResponse( + functions=[ + functions.Function(), + functions.Function(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_functions(request={}) + ).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + functions.CreateFunctionRequest, + dict, + ], +) +def test_create_function(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_function_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + client.create_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + +@pytest.mark.asyncio +async def test_create_function_async( + transport: str = "grpc_asyncio", request_type=functions.CreateFunctionRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.CreateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_function_async_from_dict(): + await test_create_function_async(request_type=dict) + + +def test_create_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.CreateFunctionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_function( + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].function + mock_val = functions.Function(name="name_value") + assert arg == mock_val + arg = args[0].function_id + mock_val = "function_id_value" + assert arg == mock_val + + +def test_create_function_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_function( + functions.CreateFunctionRequest(), + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_function( + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].function + mock_val = functions.Function(name="name_value") + assert arg == mock_val + arg = args[0].function_id + mock_val = "function_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_function( + functions.CreateFunctionRequest(), + parent="parent_value", + function=functions.Function(name="name_value"), + function_id="function_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + functions.UpdateFunctionRequest, + dict, + ], +) +def test_update_function(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_function_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + client.update_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + +@pytest.mark.asyncio +async def test_update_function_async( + transport: str = "grpc_asyncio", request_type=functions.UpdateFunctionRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.UpdateFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_function_async_from_dict(): + await test_update_function_async(request_type=dict) + + +def test_update_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "function.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.UpdateFunctionRequest() + + request.function.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "function.name=name_value", + ) in kw["metadata"] + + +def test_update_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_function( + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].function + mock_val = functions.Function(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_function_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_function( + functions.UpdateFunctionRequest(), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_function( + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].function + mock_val = functions.Function(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_function( + functions.UpdateFunctionRequest(), + function=functions.Function(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + functions.DeleteFunctionRequest, + dict, + ], +) +def test_delete_function(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_function_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + client.delete_function() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + +@pytest.mark.asyncio +async def test_delete_function_async( + transport: str = "grpc_asyncio", request_type=functions.DeleteFunctionRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.DeleteFunctionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_function_async_from_dict(): + await test_delete_function_async(request_type=dict) + + +def test_delete_function_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_function_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.DeleteFunctionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_function(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_function_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_function( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_function_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_function( + functions.DeleteFunctionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_function_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_function), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_function( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_function_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_function( + functions.DeleteFunctionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + functions.GenerateUploadUrlRequest, + dict, + ], +) +def test_generate_upload_url(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateUploadUrlResponse( + upload_url="upload_url_value", + ) + response = client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == "upload_url_value" + + +def test_generate_upload_url_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), "__call__" + ) as call: + client.generate_upload_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + +@pytest.mark.asyncio +async def test_generate_upload_url_async( + transport: str = "grpc_asyncio", request_type=functions.GenerateUploadUrlRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateUploadUrlResponse( + upload_url="upload_url_value", + ) + ) + response = await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateUploadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateUploadUrlResponse) + assert response.upload_url == "upload_url_value" + + +@pytest.mark.asyncio +async def test_generate_upload_url_async_from_dict(): + await test_generate_upload_url_async(request_type=dict) + + +def test_generate_upload_url_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), "__call__" + ) as call: + call.return_value = functions.GenerateUploadUrlResponse() + client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_upload_url_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateUploadUrlRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_upload_url), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateUploadUrlResponse() + ) + await client.generate_upload_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + functions.GenerateDownloadUrlRequest, + dict, + ], +) +def test_generate_download_url(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = functions.GenerateDownloadUrlResponse( + download_url="download_url_value", + ) + response = client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == "download_url_value" + + +def test_generate_download_url_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), "__call__" + ) as call: + client.generate_download_url() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + +@pytest.mark.asyncio +async def test_generate_download_url_async( + transport: str = "grpc_asyncio", request_type=functions.GenerateDownloadUrlRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateDownloadUrlResponse( + download_url="download_url_value", + ) + ) + response = await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.GenerateDownloadUrlRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.GenerateDownloadUrlResponse) + assert response.download_url == "download_url_value" + + +@pytest.mark.asyncio +async def test_generate_download_url_async_from_dict(): + await test_generate_download_url_async(request_type=dict) + + +def test_generate_download_url_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), "__call__" + ) as call: + call.return_value = functions.GenerateDownloadUrlResponse() + client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_download_url_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.GenerateDownloadUrlRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_download_url), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.GenerateDownloadUrlResponse() + ) + await client.generate_download_url(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + functions.ListRuntimesRequest, + dict, + ], +) +def test_list_runtimes(request_type, transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse() + response = client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.ListRuntimesResponse) + + +def test_list_runtimes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + client.list_runtimes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + + +@pytest.mark.asyncio +async def test_list_runtimes_async( + transport: str = "grpc_asyncio", request_type=functions.ListRuntimesRequest +): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) + response = await client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == functions.ListRuntimesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, functions.ListRuntimesResponse) + + +@pytest.mark.asyncio +async def test_list_runtimes_async_from_dict(): + await test_list_runtimes_async(request_type=dict) + + +def test_list_runtimes_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListRuntimesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + call.return_value = functions.ListRuntimesResponse() + client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_runtimes_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = functions.ListRuntimesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) + await client.list_runtimes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_runtimes_flattened(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_runtimes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_runtimes_flattened_error(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_runtimes( + functions.ListRuntimesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_runtimes_flattened_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_runtimes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = functions.ListRuntimesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + functions.ListRuntimesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_runtimes( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_runtimes_flattened_error_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_runtimes( + functions.ListRuntimesRequest(), + parent="parent_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FunctionServiceClient( + 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 = FunctionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FunctionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FunctionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FunctionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FunctionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +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", + ], +) +def test_transport_kind(transport_name): + transport = FunctionServiceClient.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 = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FunctionServiceGrpcTransport, + ) + + +def test_function_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FunctionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_function_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.FunctionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_function", + "list_functions", + "create_function", + "update_function", + "delete_function", + "generate_upload_url", + "generate_download_url", + "list_runtimes", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "list_locations", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_function_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FunctionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_function_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.functions_v2.services.function_service.transports.FunctionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FunctionServiceTransport() + adc.assert_called_once() + + +def test_function_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FunctionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FunctionServiceGrpcTransport, grpc_helpers), + (transports.FunctionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_function_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudfunctions.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudfunctions.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_function_service_host_no_port(transport_name): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudfunctions.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("cloudfunctions.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_function_service_host_with_port(transport_name): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudfunctions.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("cloudfunctions.googleapis.com:8000") + + +def test_function_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FunctionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_function_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FunctionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.FunctionServiceGrpcTransport, + transports.FunctionServiceGrpcAsyncIOTransport, + ], +) +def test_function_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_function_service_grpc_lro_client(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_function_service_grpc_lro_async_client(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_build_path(): + project = "squid" + location = "clam" + build = "whelk" + expected = "projects/{project}/locations/{location}/builds/{build}".format( + project=project, + location=location, + build=build, + ) + actual = FunctionServiceClient.build_path(project, location, build) + assert expected == actual + + +def test_parse_build_path(): + expected = { + "project": "octopus", + "location": "oyster", + "build": "nudibranch", + } + path = FunctionServiceClient.build_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_build_path(path) + assert expected == actual + + +def test_channel_path(): + project = "cuttlefish" + location = "mussel" + channel = "winkle" + expected = "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) + actual = FunctionServiceClient.channel_path(project, location, channel) + assert expected == actual + + +def test_parse_channel_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "channel": "abalone", + } + path = FunctionServiceClient.channel_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_channel_path(path) + assert expected == actual + + +def test_connector_path(): + project = "squid" + location = "clam" + connector = "whelk" + expected = "projects/{project}/locations/{location}/connectors/{connector}".format( + project=project, + location=location, + connector=connector, + ) + actual = FunctionServiceClient.connector_path(project, location, connector) + assert expected == actual + + +def test_parse_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "connector": "nudibranch", + } + path = FunctionServiceClient.connector_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_connector_path(path) + assert expected == actual + + +def test_function_path(): + project = "cuttlefish" + location = "mussel" + function = "winkle" + expected = "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) + actual = FunctionServiceClient.function_path(project, location, function) + assert expected == actual + + +def test_parse_function_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "function": "abalone", + } + path = FunctionServiceClient.function_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_function_path(path) + assert expected == actual + + +def test_repository_path(): + project = "squid" + location = "clam" + repository = "whelk" + expected = ( + "projects/{project}/locations/{location}/repositories/{repository}".format( + project=project, + location=location, + repository=repository, + ) + ) + actual = FunctionServiceClient.repository_path(project, location, repository) + assert expected == actual + + +def test_parse_repository_path(): + expected = { + "project": "octopus", + "location": "oyster", + "repository": "nudibranch", + } + path = FunctionServiceClient.repository_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_repository_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + service = "winkle" + expected = "projects/{project}/locations/{location}/services/{service}".format( + project=project, + location=location, + service=service, + ) + actual = FunctionServiceClient.service_path(project, location, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "service": "abalone", + } + path = FunctionServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_service_path(path) + assert expected == actual + + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + actual = FunctionServiceClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = FunctionServiceClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_topic_path(path) + assert expected == actual + + +def test_trigger_path(): + project = "oyster" + location = "nudibranch" + trigger = "cuttlefish" + expected = "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) + actual = FunctionServiceClient.trigger_path(project, location, trigger) + assert expected == actual + + +def test_parse_trigger_path(): + expected = { + "project": "mussel", + "location": "winkle", + "trigger": "nautilus", + } + path = FunctionServiceClient.trigger_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_trigger_path(path) + assert expected == actual + + +def test_worker_pool_path(): + project = "scallop" + location = "abalone" + worker_pool = "squid" + expected = ( + "projects/{project}/locations/{location}/workerPools/{worker_pool}".format( + project=project, + location=location, + worker_pool=worker_pool, + ) + ) + actual = FunctionServiceClient.worker_pool_path(project, location, worker_pool) + assert expected == actual + + +def test_parse_worker_pool_path(): + expected = { + "project": "clam", + "location": "whelk", + "worker_pool": "octopus", + } + path = FunctionServiceClient.worker_pool_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_worker_pool_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = FunctionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = FunctionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = FunctionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = FunctionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = FunctionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = FunctionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = FunctionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = FunctionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = FunctionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = FunctionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FunctionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.FunctionServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.FunctionServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = FunctionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations(transport: str = "grpc"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the 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_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = FunctionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = FunctionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (FunctionServiceClient, transports.FunctionServiceGrpcTransport), + (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )