From 7bc2d044a9cd316fda66aec321bf366c5ec03df5 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 8 Aug 2024 01:14:51 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20post-p?= =?UTF-8?q?rocessor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-cloud-functions/v1/.coveragerc | 13 - .../google-cloud-functions/v1/.flake8 | 33 - .../google-cloud-functions/v1/MANIFEST.in | 2 - .../google-cloud-functions/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-functions/v1/docs/conf.py | 376 - .../functions_v1/cloud_functions_service.rst | 10 - .../v1/docs/functions_v1/services_.rst | 6 - .../v1/docs/functions_v1/types_.rst | 6 - .../google-cloud-functions/v1/docs/index.rst | 7 - .../v1/google/cloud/functions/__init__.py | 71 - .../google/cloud/functions/gapic_version.py | 16 - .../v1/google/cloud/functions/py.typed | 2 - .../v1/google/cloud/functions_v1/__init__.py | 72 - .../cloud/functions_v1/gapic_metadata.json | 193 - .../cloud/functions_v1/gapic_version.py | 16 - .../v1/google/cloud/functions_v1/py.typed | 2 - .../cloud/functions_v1/services/__init__.py | 15 - .../cloud_functions_service/__init__.py | 22 - .../cloud_functions_service/async_client.py | 1617 ---- .../cloud_functions_service/client.py | 1984 ---- .../cloud_functions_service/pagers.py | 162 - .../transports/__init__.py | 38 - .../transports/base.py | 370 - .../transports/grpc.py | 655 -- .../transports/grpc_asyncio.py | 755 -- .../transports/rest.py | 1868 ---- .../cloud/functions_v1/types/__init__.py | 66 - .../cloud/functions_v1/types/functions.py | 1185 --- .../cloud/functions_v1/types/operations.py | 123 - .../google-cloud-functions/v1/mypy.ini | 3 - .../google-cloud-functions/v1/noxfile.py | 280 - ...d_functions_service_call_function_async.py | 53 - ...ud_functions_service_call_function_sync.py | 53 - ...functions_service_create_function_async.py | 60 - ..._functions_service_create_function_sync.py | 60 - ...functions_service_delete_function_async.py | 56 - ..._functions_service_delete_function_sync.py | 56 - ...ons_service_generate_download_url_async.py | 51 - ...ions_service_generate_download_url_sync.py | 51 - ...tions_service_generate_upload_url_async.py | 51 - ...ctions_service_generate_upload_url_sync.py | 51 - ...ud_functions_service_get_function_async.py | 52 - ...oud_functions_service_get_function_sync.py | 52 - ..._functions_service_get_iam_policy_async.py | 53 - ...d_functions_service_get_iam_policy_sync.py | 53 - ..._functions_service_list_functions_async.py | 52 - ...d_functions_service_list_functions_sync.py | 52 - ..._functions_service_set_iam_policy_async.py | 53 - ...d_functions_service_set_iam_policy_sync.py | 53 - ...ions_service_test_iam_permissions_async.py | 54 - ...tions_service_test_iam_permissions_sync.py | 54 - ...functions_service_update_function_async.py | 59 - ..._functions_service_update_function_sync.py | 59 - ...et_metadata_google.cloud.functions.v1.json | 1754 ---- .../v1/scripts/fixup_functions_v1_keywords.py | 186 - .../google-cloud-functions/v1/setup.py | 94 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/functions_v1/__init__.py | 16 - .../test_cloud_functions_service.py | 8527 ----------------- .../google-cloud-functions/v2/.coveragerc | 13 - .../google-cloud-functions/v2/.flake8 | 33 - .../google-cloud-functions/v2/MANIFEST.in | 2 - .../google-cloud-functions/v2/README.rst | 49 - .../v2/docs/_static/custom.css | 3 - .../google-cloud-functions/v2/docs/conf.py | 376 - .../v2/docs/functions_v2/function_service.rst | 10 - .../v2/docs/functions_v2/services_.rst | 6 - .../v2/docs/functions_v2/types_.rst | 6 - .../google-cloud-functions/v2/docs/index.rst | 7 - .../v2/google/cloud/functions/__init__.py | 83 - .../google/cloud/functions/gapic_version.py | 16 - .../v2/google/cloud/functions/py.typed | 2 - .../v2/google/cloud/functions_v2/__init__.py | 84 - .../cloud/functions_v2/gapic_metadata.json | 148 - .../cloud/functions_v2/gapic_version.py | 16 - .../v2/google/cloud/functions_v2/py.typed | 2 - .../cloud/functions_v2/services/__init__.py | 15 - .../services/function_service/__init__.py | 22 - .../services/function_service/async_client.py | 1651 ---- .../services/function_service/client.py | 2077 ---- .../services/function_service/pagers.py | 162 - .../function_service/transports/__init__.py | 38 - .../function_service/transports/base.py | 318 - .../function_service/transports/grpc.py | 651 -- .../transports/grpc_asyncio.py | 696 -- .../function_service/transports/rest.py | 1654 ---- .../cloud/functions_v2/types/__init__.py | 76 - .../cloud/functions_v2/types/functions.py | 1635 ---- .../google-cloud-functions/v2/mypy.ini | 3 - .../google-cloud-functions/v2/noxfile.py | 280 - ..._function_service_create_function_async.py | 56 - ...d_function_service_create_function_sync.py | 56 - ..._function_service_delete_function_async.py | 56 - ...d_function_service_delete_function_sync.py | 56 - ...ion_service_generate_download_url_async.py | 52 - ...tion_service_generate_download_url_sync.py | 52 - ...ction_service_generate_upload_url_async.py | 52 - ...nction_service_generate_upload_url_sync.py | 52 - ...ted_function_service_get_function_async.py | 52 - ...ated_function_service_get_function_sync.py | 52 - ...d_function_service_list_functions_async.py | 53 - ...ed_function_service_list_functions_sync.py | 53 - ...ed_function_service_list_runtimes_async.py | 52 - ...ted_function_service_list_runtimes_sync.py | 52 - ..._function_service_update_function_async.py | 55 - ...d_function_service_update_function_sync.py | 55 - ...et_metadata_google.cloud.functions.v2.json | 1311 --- .../v2/scripts/fixup_functions_v2_keywords.py | 183 - .../google-cloud-functions/v2/setup.py | 94 - .../v2/testing/constraints-3.10.txt | 7 - .../v2/testing/constraints-3.11.txt | 7 - .../v2/testing/constraints-3.12.txt | 7 - .../v2/testing/constraints-3.7.txt | 11 - .../v2/testing/constraints-3.8.txt | 7 - .../v2/testing/constraints-3.9.txt | 7 - .../v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/functions_v2/__init__.py | 16 - .../functions_v2/test_function_service.py | 8010 ---------------- .../google/cloud/functions/gapic_version.py | 2 +- .../cloud/functions_v1/gapic_version.py | 2 +- .../cloud/functions_v1/types/functions.py | 35 +- .../cloud/functions_v2/gapic_version.py | 2 +- ...et_metadata_google.cloud.functions.v1.json | 2 +- ...et_metadata_google.cloud.functions.v2.json | 2 +- .../test_cloud_functions_service.py | 9 + 136 files changed, 34 insertions(+), 42597 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-functions/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-functions/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-functions/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-functions/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/cloud_functions_service.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/py.typed delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/functions.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/operations.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-functions/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json delete mode 100644 owl-bot-staging/google-cloud-functions/v1/scripts/fixup_functions_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-functions/v2/.flake8 delete mode 100644 owl-bot-staging/google-cloud-functions/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-functions/v2/README.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/function_service.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/services_.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/types_.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/py.typed delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/py.typed delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/client.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/functions.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-functions/v2/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json delete mode 100644 owl-bot-staging/google-cloud-functions/v2/scripts/fixup_functions_v2_keywords.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/setup.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-functions/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/test_function_service.py diff --git a/owl-bot-staging/google-cloud-functions/v1/.coveragerc b/owl-bot-staging/google-cloud-functions/v1/.coveragerc deleted file mode 100644 index 3409ddad4fe3..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__init__.py - google/cloud/functions/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-functions/v1/.flake8 b/owl-bot-staging/google-cloud-functions/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-functions/v1/MANIFEST.in b/owl-bot-staging/google-cloud-functions/v1/MANIFEST.in deleted file mode 100644 index 9e8399a1b4a5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v1 *.py diff --git a/owl-bot-staging/google-cloud-functions/v1/README.rst b/owl-bot-staging/google-cloud-functions/v1/README.rst deleted file mode 100644 index 533650ad477c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Functions API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-functions/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/conf.py b/owl-bot-staging/google-cloud-functions/v1/docs/conf.py deleted file mode 100644 index 92a2c45f25e2..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# -# google-cloud-functions documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-functions" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-functions-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-functions.tex", - u"google-cloud-functions Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-functions", - u"Google Cloud Functions Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/cloud_functions_service.rst b/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/cloud_functions_service.rst deleted file mode 100644 index 36d0114234de..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/cloud_functions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -CloudFunctionsService ---------------------------------------- - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service - :members: - :inherited-members: - -.. automodule:: google.cloud.functions_v1.services.cloud_functions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/services_.rst b/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/services_.rst deleted file mode 100644 index 89ae970cb80e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Functions v1 API -========================================== -.. toctree:: - :maxdepth: 2 - - cloud_functions_service diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/types_.rst b/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/types_.rst deleted file mode 100644 index e2d24d0383c7..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/functions_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Functions v1 API -======================================= - -.. automodule:: google.cloud.functions_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-functions/v1/docs/index.rst b/owl-bot-staging/google-cloud-functions/v1/docs/index.rst deleted file mode 100644 index dc30f6d35f69..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v1/services - functions_v1/types diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/__init__.py deleted file mode 100644 index 3fc3363b7024..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.cloud.functions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.functions_v1.services.cloud_functions_service.client import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service.async_client import CloudFunctionsServiceAsyncClient - -from google.cloud.functions_v1.types.functions import CallFunctionRequest -from google.cloud.functions_v1.types.functions import CallFunctionResponse -from google.cloud.functions_v1.types.functions import CloudFunction -from google.cloud.functions_v1.types.functions import CreateFunctionRequest -from google.cloud.functions_v1.types.functions import DeleteFunctionRequest -from google.cloud.functions_v1.types.functions import EventTrigger -from google.cloud.functions_v1.types.functions import FailurePolicy -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v1.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v1.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v1.types.functions import GetFunctionRequest -from google.cloud.functions_v1.types.functions import HttpsTrigger -from google.cloud.functions_v1.types.functions import ListFunctionsRequest -from google.cloud.functions_v1.types.functions import ListFunctionsResponse -from google.cloud.functions_v1.types.functions import SecretEnvVar -from google.cloud.functions_v1.types.functions import SecretVolume -from google.cloud.functions_v1.types.functions import SourceRepository -from google.cloud.functions_v1.types.functions import UpdateFunctionRequest -from google.cloud.functions_v1.types.functions import CloudFunctionStatus -from google.cloud.functions_v1.types.operations import OperationMetadataV1 -from google.cloud.functions_v1.types.operations import OperationType - -__all__ = ('CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/gapic_version.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/py.typed b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/py.typed deleted file mode 100644 index 982ebb18c324..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/__init__.py deleted file mode 100644 index 79a31e6826d2..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.cloud.functions_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.cloud_functions_service import CloudFunctionsServiceClient -from .services.cloud_functions_service import CloudFunctionsServiceAsyncClient - -from .types.functions import CallFunctionRequest -from .types.functions import CallFunctionResponse -from .types.functions import CloudFunction -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventTrigger -from .types.functions import FailurePolicy -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import HttpsTrigger -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import SourceRepository -from .types.functions import UpdateFunctionRequest -from .types.functions import CloudFunctionStatus -from .types.operations import OperationMetadataV1 -from .types.operations import OperationType - -__all__ = ( - 'CloudFunctionsServiceAsyncClient', -'CallFunctionRequest', -'CallFunctionResponse', -'CloudFunction', -'CloudFunctionStatus', -'CloudFunctionsServiceClient', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'EventTrigger', -'FailurePolicy', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'HttpsTrigger', -'ListFunctionsRequest', -'ListFunctionsResponse', -'OperationMetadataV1', -'OperationType', -'SecretEnvVar', -'SecretVolume', -'SourceRepository', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_metadata.json deleted file mode 100644 index 22d9da750c6e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_metadata.json +++ /dev/null @@ -1,193 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.functions_v1", - "protoPackage": "google.cloud.functions.v1", - "schema": "1.0", - "services": { - "CloudFunctionsService": { - "clients": { - "grpc": { - "libraryClient": "CloudFunctionsServiceClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CloudFunctionsServiceAsyncClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - }, - "rest": { - "libraryClient": "CloudFunctionsServiceClient", - "rpcs": { - "CallFunction": { - "methods": [ - "call_function" - ] - }, - "CreateFunction": { - "methods": [ - "create_function" - ] - }, - "DeleteFunction": { - "methods": [ - "delete_function" - ] - }, - "GenerateDownloadUrl": { - "methods": [ - "generate_download_url" - ] - }, - "GenerateUploadUrl": { - "methods": [ - "generate_upload_url" - ] - }, - "GetFunction": { - "methods": [ - "get_function" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFunctions": { - "methods": [ - "list_functions" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFunction": { - "methods": [ - "update_function" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_version.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/py.typed b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/py.typed deleted file mode 100644 index 982ebb18c324..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py deleted file mode 100644 index 176cceedb490..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 .client import CloudFunctionsServiceClient -from .async_client import CloudFunctionsServiceAsyncClient - -__all__ = ( - 'CloudFunctionsServiceClient', - 'CloudFunctionsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py deleted file mode 100644 index 717715a38c2f..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/async_client.py +++ /dev/null @@ -1,1617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.functions_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .client import CloudFunctionsServiceClient - - -class CloudFunctionsServiceAsyncClient: - """A service that application uses to manipulate triggers and - functions. - """ - - _client: CloudFunctionsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - - cloud_function_path = staticmethod(CloudFunctionsServiceClient.cloud_function_path) - parse_cloud_function_path = staticmethod(CloudFunctionsServiceClient.parse_cloud_function_path) - crypto_key_path = staticmethod(CloudFunctionsServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(CloudFunctionsServiceClient.parse_crypto_key_path) - repository_path = staticmethod(CloudFunctionsServiceClient.repository_path) - parse_repository_path = staticmethod(CloudFunctionsServiceClient.parse_repository_path) - common_billing_account_path = staticmethod(CloudFunctionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudFunctionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CloudFunctionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CloudFunctionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudFunctionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudFunctionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CloudFunctionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CloudFunctionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CloudFunctionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CloudFunctionsServiceClient.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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_info.__func__(CloudFunctionsServiceAsyncClient, 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: - CloudFunctionsServiceAsyncClient: The constructed client. - """ - return CloudFunctionsServiceClient.from_service_account_file.__func__(CloudFunctionsServiceAsyncClient, 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 variable 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 CloudFunctionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(CloudFunctionsServiceClient).get_transport_class, type(CloudFunctionsServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudFunctionsServiceTransport, Callable[..., CloudFunctionsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions service async 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 (Optional[Union[str,CloudFunctionsServiceTransport,Callable[..., CloudFunctionsServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the CloudFunctionsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = CloudFunctionsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_functions(self, - request: Optional[Union[functions.ListFunctionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.functions_v1.types.ListFunctionsRequest, dict]]): - The request object. Request for the ``ListFunctions`` method. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.services.cloud_functions_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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.ListFunctionsRequest): - request = functions.ListFunctionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_function(self, - request: Optional[Union[functions.GetFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.functions_v1.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_async.AsyncRetry): 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_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_function(self, - request: Optional[Union[functions.CreateFunctionRequest, dict]] = None, - *, - location: Optional[str] = None, - function: Optional[functions.CloudFunction] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # 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 (Optional[Union[google.cloud.functions_v1.types.CreateFunctionRequest, dict]]): - The request object. Request for the ``CreateFunction`` method. - location (:class:`str`): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - Required. Function to be created. - This corresponds to the ``function`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers 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([location, function]) - 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.CreateFunctionRequest): - request = functions.CreateFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._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(( - ("location", request.location), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_function(self, - request: Optional[Union[functions.UpdateFunctionRequest, dict]] = None, - *, - function: Optional[functions.CloudFunction] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates existing function. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # 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 (Optional[Union[google.cloud.functions_v1.types.UpdateFunctionRequest, dict]]): - The request object. Request for the ``UpdateFunction`` method. - function (:class:`google.cloud.functions_v1.types.CloudFunction`): - 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. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers 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]) - 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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 - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_function(self, - request: Optional[Union[functions.DeleteFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.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 (Optional[Union[google.cloud.functions_v1.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_async.AsyncRetry): 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); - - } - - """ - # 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def call_function(self, - request: Optional[Union[functions.CallFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]]): - The request object. Request for the ``CallFunction`` method. - name (:class:`str`): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`str`): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.types.CallFunctionResponse: - Response of CallFunction 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([name, data]) - 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.CallFunctionRequest): - request = functions.CallFunctionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.call_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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_upload_url(self, - request: Optional[Union[functions.GenerateUploadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - Source file size should not exceed 100MB limit. - - 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`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.functions_v1.types.GenerateUploadUrlRequest, dict]]): - The request object. Request of ``GenerateSourceUploadUrl`` method. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.GenerateDownloadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 minutes after - generation. - For more information about the signed URL usage see: - - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.functions_v1.types.GenerateDownloadUrlRequest, dict]]): - The request object. Request of ``GenerateDownloadUrl`` method. - retry (google.api_core.retry_async.AsyncRetry): 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_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - retry (google.api_core.retry_async.AsyncRetry): 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.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_iam_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - retry (google.api_core.retry_async.AsyncRetry): 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.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_iam_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - retry (google.api_core.retry_async.AsyncRetry): 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.iam.v1.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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "CloudFunctionsServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CloudFunctionsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py deleted file mode 100644 index 4715f9fbc3e8..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/client.py +++ /dev/null @@ -1,1984 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.functions_v1 import gapic_version as package_version - -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.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CloudFunctionsServiceGrpcTransport -from .transports.grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .transports.rest import CloudFunctionsServiceRestTransport - - -class CloudFunctionsServiceClientMeta(type): - """Metaclass for the CloudFunctionsService 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[CloudFunctionsServiceTransport]] - _transport_registry["grpc"] = CloudFunctionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CloudFunctionsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = CloudFunctionsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CloudFunctionsServiceTransport]: - """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 CloudFunctionsServiceClient(metaclass=CloudFunctionsServiceClientMeta): - """A service that application uses to manipulate triggers and - functions. - """ - - @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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudfunctions.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudfunctions.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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: - CloudFunctionsServiceClient: 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: - CloudFunctionsServiceClient: 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) -> CloudFunctionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CloudFunctionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: - """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - - @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: - """Parses a cloud_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 crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?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 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): - """Deprecated. 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 variable 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. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - CloudFunctionsServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudFunctionsServiceTransport, Callable[..., CloudFunctionsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the cloud functions 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 (Optional[Union[str,CloudFunctionsServiceTransport,Callable[..., CloudFunctionsServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the CloudFunctionsServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudFunctionsServiceClient._read_environment_variables() - self._client_cert_source = CloudFunctionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = CloudFunctionsServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, CloudFunctionsServiceTransport) - if transport_provided: - # transport is a CloudFunctionsServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(CloudFunctionsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - CloudFunctionsServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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_init: Union[Type[CloudFunctionsServiceTransport], Callable[..., CloudFunctionsServiceTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., CloudFunctionsServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def list_functions(self, - request: Optional[Union[functions.ListFunctionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # 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_v1.types.ListFunctionsRequest, dict]): - The request object. Request for the ``ListFunctions`` 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_v1.services.cloud_functions_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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.ListFunctionsRequest): - request = functions.ListFunctionsRequest(request) - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_function(self, - request: Optional[Union[functions.GetFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CloudFunction: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.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_v1.types.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_function(self, - request: Optional[Union[functions.CreateFunctionRequest, dict]] = None, - *, - location: Optional[str] = None, - function: Optional[functions.CloudFunction] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # 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_v1.types.CreateFunctionRequest, dict]): - The request object. Request for the ``CreateFunction`` method. - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - This corresponds to the ``function`` 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_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers 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([location, function]) - 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.CreateFunctionRequest): - request = functions.CreateFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if function is not None: - request.function = function - - # 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(( - ("location", request.location), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_function(self, - request: Optional[Union[functions.UpdateFunctionRequest, dict]] = None, - *, - function: Optional[functions.CloudFunction] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates existing function. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # 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_v1.types.UpdateFunctionRequest, dict]): - The request object. Request for the ``UpdateFunction`` method. - function (google.cloud.functions_v1.types.CloudFunction): - 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. - 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_v1.types.CloudFunction` Describes a Cloud Function that contains user computation executed in - response to an event. It encapsulate function and - triggers 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]) - 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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 - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.CloudFunction, - metadata_type=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_function(self, - request: Optional[Union[functions.DeleteFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.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_v1.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); - - } - - """ - # 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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=operations.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def call_function(self, - request: Optional[Union[functions.CallFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.CallFunctionResponse: - r"""Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.types.CallFunctionRequest, dict]): - The request object. Request for the ``CallFunction`` method. - name (str): - Required. The name of the function to - be called. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (str): - Required. Input to be passed to the - function. - - This corresponds to the ``data`` 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_v1.types.CallFunctionResponse: - Response of CallFunction 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([name, data]) - 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, functions.CallFunctionRequest): - request = functions.CallFunctionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.call_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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_upload_url(self, - request: Optional[Union[functions.GenerateUploadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - Source file size should not exceed 100MB limit. - - 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`` - - ``x-goog-content-length-range: 0,104857600`` - - And this header SHOULD NOT be specified: - - - ``Authorization: Bearer YOUR_TOKEN`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.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_v1.types.GenerateUploadUrlResponse: - Response of GenerateSourceUploadUrl method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_download_url(self, - request: Optional[Union[functions.GenerateDownloadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 minutes after - generation. - For more information about the signed URL usage see: - - https://cloud.google.com/storage/docs/access-control/signed-urls - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - - def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.functions_v1.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_v1.types.GenerateDownloadUrlResponse: - Response of GenerateDownloadUrl method. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified - function. Replaces any existing policy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - 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: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - 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: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""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. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import functions_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - 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: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "CloudFunctionsServiceClient": - 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: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CloudFunctionsServiceClient", -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py deleted file mode 100644 index bc89cb7f1bca..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.functions_v1.types import functions - - -class ListFunctionsPager: - """A pager for iterating through ``list_functions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.functions_v1.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_v1.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, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - The initial response object. - 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. - """ - self._method = method - self._request = functions.ListFunctionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[functions.CloudFunction]: - 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_v1.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_v1.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, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_v1.types.ListFunctionsRequest): - The initial request object. - response (google.cloud.functions_v1.types.ListFunctionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): 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. - """ - self._method = method - self._request = functions.ListFunctionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[functions.CloudFunction]: - 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/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py deleted file mode 100644 index 4aeb1f19c4eb..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 CloudFunctionsServiceTransport -from .grpc import CloudFunctionsServiceGrpcTransport -from .grpc_asyncio import CloudFunctionsServiceGrpcAsyncIOTransport -from .rest import CloudFunctionsServiceRestTransport -from .rest import CloudFunctionsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CloudFunctionsServiceTransport]] -_transport_registry['grpc'] = CloudFunctionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CloudFunctionsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CloudFunctionsServiceRestTransport - -__all__ = ( - 'CloudFunctionsServiceTransport', - 'CloudFunctionsServiceGrpcTransport', - 'CloudFunctionsServiceGrpcAsyncIOTransport', - 'CloudFunctionsServiceRestTransport', - 'CloudFunctionsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py deleted file mode 100644 index d412267be604..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/base.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 - -from google.cloud.functions_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -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 import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.functions_v1.types import functions -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 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class CloudFunctionsServiceTransport(abc.ABC): - """Abstract transport class for CloudFunctionsService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudfunctions.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[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 (default: 'cloudfunctions.googleapis.com'). - 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 not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - 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 - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_functions: gapic_v1.method.wrap_method( - self.list_functions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_function: gapic_v1.method.wrap_method( - self.get_function, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.create_function: gapic_v1.method.wrap_method( - self.create_function, - default_timeout=600.0, - client_info=client_info, - ), - self.update_function: gapic_v1.method.wrap_method( - self.update_function, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_function: gapic_v1.method.wrap_method( - self.delete_function, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.call_function: gapic_v1.method.wrap_method( - self.call_function, - default_timeout=600.0, - 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.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - Union[ - functions.ListFunctionsResponse, - Awaitable[functions.ListFunctionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Union[ - functions.CloudFunction, - Awaitable[functions.CloudFunction] - ]]: - 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 call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Union[ - functions.CallFunctionResponse, - Awaitable[functions.CallFunctionResponse] - ]]: - 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 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_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 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__ = ( - 'CloudFunctionsServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py deleted file mode 100644 index a2624a11a67f..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc.py +++ /dev/null @@ -1,655 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_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 - -import grpc # type: ignore - -from google.cloud.functions_v1.types import functions -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 .base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO - - -class CloudFunctionsServiceGrpcTransport(CloudFunctionsServiceTransport): - """gRPC backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[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 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.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.CloudFunction]: - 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], - ~.CloudFunction]: - 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.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @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.v1.CloudFunctionsService/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.v1.CloudFunctionsService/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.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - functions.CallFunctionResponse]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - ~.CallFunctionResponse]: - 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 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_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. - - Source file size should not exceed 100MB limit. - - 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`` - - ``x-goog-content-length-range: 0,104857600`` - - 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.v1.CloudFunctionsService/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 minutes after - 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.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @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.cloud.functions.v1.CloudFunctionsService/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.cloud.functions.v1.CloudFunctionsService/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.cloud.functions.v1.CloudFunctionsService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - 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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CloudFunctionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py deleted file mode 100644 index fc50a48bc381..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,755 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.functions_v1.types import functions -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 .base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CloudFunctionsServiceGrpcTransport - - -class CloudFunctionsServiceGrpcAsyncIOTransport(CloudFunctionsServiceTransport): - """gRPC AsyncIO backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - 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: Optional[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`. - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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 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.v1.CloudFunctionsService/ListFunctions', - request_serializer=functions.ListFunctionsRequest.serialize, - response_deserializer=functions.ListFunctionsResponse.deserialize, - ) - return self._stubs['list_functions'] - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - Awaitable[functions.CloudFunction]]: - 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[~.CloudFunction]]: - 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.v1.CloudFunctionsService/GetFunction', - request_serializer=functions.GetFunctionRequest.serialize, - response_deserializer=functions.CloudFunction.deserialize, - ) - return self._stubs['get_function'] - - @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.v1.CloudFunctionsService/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.v1.CloudFunctionsService/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.v1.CloudFunctionsService/DeleteFunction', - request_serializer=functions.DeleteFunctionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_function'] - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - Awaitable[functions.CallFunctionResponse]]: - r"""Return a callable for the call function method over gRPC. - - Synchronously invokes a deployed Cloud Function. To be used for - testing purposes as very limited traffic is allowed. For more - information on the actual limits, refer to `Rate - Limits `__. - - Returns: - Callable[[~.CallFunctionRequest], - Awaitable[~.CallFunctionResponse]]: - 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 'call_function' not in self._stubs: - self._stubs['call_function'] = self.grpc_channel.unary_unary( - '/google.cloud.functions.v1.CloudFunctionsService/CallFunction', - request_serializer=functions.CallFunctionRequest.serialize, - response_deserializer=functions.CallFunctionResponse.deserialize, - ) - return self._stubs['call_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. - - Source file size should not exceed 100MB limit. - - 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`` - - ``x-goog-content-length-range: 0,104857600`` - - 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.v1.CloudFunctionsService/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 minutes after - 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.v1.CloudFunctionsService/GenerateDownloadUrl', - request_serializer=functions.GenerateDownloadUrlRequest.serialize, - response_deserializer=functions.GenerateDownloadUrlResponse.deserialize, - ) - return self._stubs['generate_download_url'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[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], - Awaitable[~.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.cloud.functions.v1.CloudFunctionsService/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], - Awaitable[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], - Awaitable[~.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.cloud.functions.v1.CloudFunctionsService/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], - Awaitable[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], - Awaitable[~.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.cloud.functions.v1.CloudFunctionsService/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_functions: gapic_v1.method_async.wrap_method( - self.list_functions, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.get_function: gapic_v1.method_async.wrap_method( - self.get_function, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.create_function: gapic_v1.method_async.wrap_method( - self.create_function, - default_timeout=600.0, - client_info=client_info, - ), - self.update_function: gapic_v1.method_async.wrap_method( - self.update_function, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.delete_function: gapic_v1.method_async.wrap_method( - self.delete_function, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=600.0, - ), - default_timeout=600.0, - client_info=client_info, - ), - self.call_function: gapic_v1.method_async.wrap_method( - self.call_function, - default_timeout=600.0, - client_info=client_info, - ), - self.generate_upload_url: gapic_v1.method_async.wrap_method( - self.generate_upload_url, - default_timeout=None, - client_info=client_info, - ), - self.generate_download_url: gapic_v1.method_async.wrap_method( - self.generate_download_url, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - } - - 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"] - - -__all__ = ( - 'CloudFunctionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py deleted file mode 100644 index 32c5abe022c9..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/services/cloud_functions_service/transports/rest.py +++ /dev/null @@ -1,1868 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.functions_v1.types import functions -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import CloudFunctionsServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class CloudFunctionsServiceRestInterceptor: - """Interceptor for CloudFunctionsService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the CloudFunctionsServiceRestTransport. - - .. code-block:: python - class MyCustomCloudFunctionsServiceInterceptor(CloudFunctionsServiceRestInterceptor): - def pre_call_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_call_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_download_url(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_download_url(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_upload_url(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_upload_url(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_functions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_functions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_function(self, response): - logging.log(f"Received response: {response}") - return response - - transport = CloudFunctionsServiceRestTransport(interceptor=MyCustomCloudFunctionsServiceInterceptor()) - client = CloudFunctionsServiceClient(transport=transport) - - - """ - def pre_call_function(self, request: functions.CallFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.CallFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for call_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_call_function(self, response: functions.CallFunctionResponse) -> functions.CallFunctionResponse: - """Post-rpc interceptor for call_function - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_create_function(self, request: functions.CreateFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.CreateFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_create_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_function - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_delete_function(self, request: functions.DeleteFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.DeleteFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_delete_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_function - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_generate_download_url(self, request: functions.GenerateDownloadUrlRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GenerateDownloadUrlRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_download_url - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_generate_download_url(self, response: functions.GenerateDownloadUrlResponse) -> functions.GenerateDownloadUrlResponse: - """Post-rpc interceptor for generate_download_url - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_generate_upload_url(self, request: functions.GenerateUploadUrlRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GenerateUploadUrlRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_upload_url - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_generate_upload_url(self, response: functions.GenerateUploadUrlResponse) -> functions.GenerateUploadUrlResponse: - """Post-rpc interceptor for generate_upload_url - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_get_function(self, request: functions.GetFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GetFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_get_function(self, response: functions.CloudFunction) -> functions.CloudFunction: - """Post-rpc interceptor for get_function - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy(self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_list_functions(self, request: functions.ListFunctionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.ListFunctionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_functions - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_list_functions(self, response: functions.ListFunctionsResponse) -> functions.ListFunctionsResponse: - """Post-rpc interceptor for list_functions - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy(self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions(self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_test_iam_permissions(self, response: iam_policy_pb2.TestIamPermissionsResponse) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_update_function(self, request: functions.UpdateFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.UpdateFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_update_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_function - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the CloudFunctionsService server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the CloudFunctionsService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class CloudFunctionsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: CloudFunctionsServiceRestInterceptor - - -class CloudFunctionsServiceRestTransport(CloudFunctionsServiceTransport): - """REST backend transport for CloudFunctionsService. - - A service that application uses to manipulate triggers and - functions. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'cloudfunctions.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[CloudFunctionsServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or CloudFunctionsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CallFunction(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("CallFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.CallFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.CallFunctionResponse: - r"""Call the call function method over HTTP. - - Args: - request (~.functions.CallFunctionRequest): - The request object. Request for the ``CallFunction`` 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: - ~.functions.CallFunctionResponse: - Response of ``CallFunction`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/functions/*}:call', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_call_function(request, metadata) - pb_request = functions.CallFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.CallFunctionResponse() - pb_resp = functions.CallFunctionResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_call_function(resp) - return resp - - class _CreateFunction(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("CreateFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.CreateFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create function method over HTTP. - - Args: - request (~.functions.CreateFunctionRequest): - The request object. Request for the ``CreateFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{location=projects/*/locations/*}/functions', - 'body': 'function', - }, - ] - request, metadata = self._interceptor.pre_create_function(request, metadata) - pb_request = functions.CreateFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_function(resp) - return resp - - class _DeleteFunction(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("DeleteFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.DeleteFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete function method over HTTP. - - Args: - request (~.functions.DeleteFunctionRequest): - The request object. Request for the ``DeleteFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/functions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_function(request, metadata) - pb_request = functions.DeleteFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_function(resp) - return resp - - class _GenerateDownloadUrl(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("GenerateDownloadUrl") - - def __call__(self, - request: functions.GenerateDownloadUrlRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.GenerateDownloadUrlResponse: - r"""Call the generate download url method over HTTP. - - Args: - request (~.functions.GenerateDownloadUrlRequest): - 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: - ~.functions.GenerateDownloadUrlResponse: - Response of ``GenerateDownloadUrl`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/functions/*}:generateDownloadUrl', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_download_url(request, metadata) - pb_request = functions.GenerateDownloadUrlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.GenerateDownloadUrlResponse() - pb_resp = functions.GenerateDownloadUrlResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_download_url(resp) - return resp - - class _GenerateUploadUrl(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("GenerateUploadUrl") - - def __call__(self, - request: functions.GenerateUploadUrlRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.GenerateUploadUrlResponse: - r"""Call the generate upload url method over HTTP. - - Args: - request (~.functions.GenerateUploadUrlRequest): - 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: - ~.functions.GenerateUploadUrlResponse: - Response of ``GenerateSourceUploadUrl`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/functions:generateUploadUrl', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_upload_url(request, metadata) - pb_request = functions.GenerateUploadUrlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.GenerateUploadUrlResponse() - pb_resp = functions.GenerateUploadUrlResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_upload_url(resp) - return resp - - class _GetFunction(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("GetFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.GetFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.CloudFunction: - r"""Call the get function method over HTTP. - - Args: - request (~.functions.GetFunctionRequest): - The request object. Request for the ``GetFunction`` 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: - ~.functions.CloudFunction: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulate - function and triggers configurations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/functions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_function(request, metadata) - pb_request = functions.GetFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.CloudFunction() - pb_resp = functions.CloudFunction.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_function(resp) - return resp - - class _GetIamPolicy(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - r"""Call the get iam policy method over HTTP. - - Args: - request (~.iam_policy_pb2.GetIamPolicyRequest): - The request object. Request message for ``GetIamPolicy`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **JSON example:** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": [ - "user:eve@example.com" - ], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **YAML example:** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/functions/*}:getIamPolicy', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _ListFunctions(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("ListFunctions") - - def __call__(self, - request: functions.ListFunctionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.ListFunctionsResponse: - r"""Call the list functions method over HTTP. - - Args: - request (~.functions.ListFunctionsRequest): - The request object. Request for the ``ListFunctions`` 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: - ~.functions.ListFunctionsResponse: - Response for the ``ListFunctions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/functions', - }, - ] - request, metadata = self._interceptor.pre_list_functions(request, metadata) - pb_request = functions.ListFunctionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.ListFunctionsResponse() - pb_resp = functions.ListFunctionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_functions(resp) - return resp - - class _SetIamPolicy(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - r"""Call the set iam policy method over HTTP. - - Args: - request (~.iam_policy_pb2.SetIamPolicyRequest): - The request object. Request message for ``SetIamPolicy`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **JSON example:** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": [ - "user:eve@example.com" - ], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **YAML example:** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/functions/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Call the test iam permissions method over HTTP. - - Args: - request (~.iam_policy_pb2.TestIamPermissionsRequest): - The request object. Request message for ``TestIamPermissions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/functions/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateFunction(CloudFunctionsServiceRestStub): - def __hash__(self): - return hash("UpdateFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.UpdateFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update function method over HTTP. - - Args: - request (~.functions.UpdateFunctionRequest): - The request object. Request for the ``UpdateFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{function.name=projects/*/locations/*/functions/*}', - 'body': 'function', - }, - ] - request, metadata = self._interceptor.pre_update_function(request, metadata) - pb_request = functions.UpdateFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_function(resp) - return resp - - @property - def call_function(self) -> Callable[ - [functions.CallFunctionRequest], - functions.CallFunctionResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CallFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateDownloadUrl(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateUploadUrl(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.CloudFunction]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFunctions(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(CloudFunctionsServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(CloudFunctionsServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(CloudFunctionsServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'CloudFunctionsServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/__init__.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/__init__.py deleted file mode 100644 index d47d09c7f6aa..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/__init__.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 ( - CallFunctionRequest, - CallFunctionResponse, - CloudFunction, - CreateFunctionRequest, - DeleteFunctionRequest, - EventTrigger, - FailurePolicy, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - HttpsTrigger, - ListFunctionsRequest, - ListFunctionsResponse, - SecretEnvVar, - SecretVolume, - SourceRepository, - UpdateFunctionRequest, - CloudFunctionStatus, -) -from .operations import ( - OperationMetadataV1, - OperationType, -) - -__all__ = ( - 'CallFunctionRequest', - 'CallFunctionResponse', - 'CloudFunction', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventTrigger', - 'FailurePolicy', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'HttpsTrigger', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'SecretEnvVar', - 'SecretVolume', - 'SourceRepository', - 'UpdateFunctionRequest', - 'CloudFunctionStatus', - 'OperationMetadataV1', - 'OperationType', -) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/functions.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/functions.py deleted file mode 100644 index 49c70b83904b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/functions.py +++ /dev/null @@ -1,1185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'CloudFunctionStatus', - 'CloudFunction', - 'SourceRepository', - 'HttpsTrigger', - 'EventTrigger', - 'FailurePolicy', - 'SecretEnvVar', - 'SecretVolume', - 'CreateFunctionRequest', - 'UpdateFunctionRequest', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'DeleteFunctionRequest', - 'CallFunctionRequest', - 'CallFunctionResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - }, -) - - -class CloudFunctionStatus(proto.Enum): - r"""Describes the current stage of a deployment. - - Values: - CLOUD_FUNCTION_STATUS_UNSPECIFIED (0): - Not specified. Invalid state. - ACTIVE (1): - Function has been successfully deployed and - is serving. - OFFLINE (2): - Function deployment failed and the function - isn’t serving. - DEPLOY_IN_PROGRESS (3): - Function is being created or updated. - DELETE_IN_PROGRESS (4): - Function is being deleted. - UNKNOWN (5): - Function deployment failed and the function - serving state is undefined. The function should - be updated or deleted to move it out of this - state. - """ - CLOUD_FUNCTION_STATUS_UNSPECIFIED = 0 - ACTIVE = 1 - OFFLINE = 2 - DEPLOY_IN_PROGRESS = 3 - DELETE_IN_PROGRESS = 4 - UNKNOWN = 5 - - -class CloudFunction(proto.Message): - r"""Describes a Cloud Function that contains user computation - executed in response to an event. It encapsulate function and - triggers configurations. - - 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: - name (str): - A user-defined name of the function. Function names must be - unique globally and match pattern - ``projects/*/locations/*/functions/*`` - description (str): - User-provided description of a function. - source_archive_url (str): - The Google Cloud Storage URL, starting with ``gs://``, - pointing to the zip archive which contains the function. - - This field is a member of `oneof`_ ``source_code``. - source_repository (google.cloud.functions_v1.types.SourceRepository): - **Beta Feature** - - The source repository where a function is hosted. - - This field is a member of `oneof`_ ``source_code``. - source_upload_url (str): - The Google Cloud Storage signed URL used for source - uploading, generated by calling - [google.cloud.functions.v1.GenerateUploadUrl]. - - The signature is validated on write methods (Create, Update) - The signature is stripped from the Function object on read - methods (Get, List) - - This field is a member of `oneof`_ ``source_code``. - https_trigger (google.cloud.functions_v1.types.HttpsTrigger): - An HTTPS endpoint type of source that can be - triggered via URL. - - This field is a member of `oneof`_ ``trigger``. - event_trigger (google.cloud.functions_v1.types.EventTrigger): - A source that fires events in response to a - condition in another service. - - This field is a member of `oneof`_ ``trigger``. - status (google.cloud.functions_v1.types.CloudFunctionStatus): - Output only. Status of the function - deployment. - entry_point (str): - The name of the function (as defined in - source code) that will be executed. Defaults to - the resource name suffix (ID of the function), - if not specified. - 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 `__. - timeout (google.protobuf.duration_pb2.Duration): - 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_mb (int): - The amount of memory in MB available for a - function. Defaults to 256MB. - service_account_email (str): - The email of the function's service account. If empty, - defaults to ``{project_id}@appspot.gserviceaccount.com``. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of a - Cloud Function. - version_id (int): - Output only. The version identifier of the - Cloud Function. Each deployment attempt results - in a new version of a function being created. - labels (MutableMapping[str, str]): - Labels associated with this Cloud Function. - environment_variables (MutableMapping[str, str]): - Environment variables that shall be available - during function execution. - build_environment_variables (MutableMapping[str, str]): - Build environment variables that shall be - available during build time. - network (str): - Deprecated: use vpc_connector - max_instances (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_instances (int): - A lower bound for the number function - instances that may coexist at a given time. - vpc_connector (str): - The VPC Network Connector that this cloud function can - connect to. It can be either the fully-qualified URI, or the - short name of the network connector resource. The format of - this field is ``projects/*/locations/*/connectors/*`` - - This field is mutually exclusive with ``network`` field and - will eventually replace it. - - See `the VPC - documentation `__ - for more information on connecting Cloud projects. - vpc_connector_egress_settings (google.cloud.functions_v1.types.CloudFunction.VpcConnectorEgressSettings): - The egress settings for the connector, - controlling what traffic is diverted through it. - ingress_settings (google.cloud.functions_v1.types.CloudFunction.IngressSettings): - The ingress settings for the function, - controlling what traffic can reach it. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function resources. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - If specified, you must also provide an artifact registry - repository using the ``docker_repository`` field that was - created with the same KMS crypto key. - - The following service accounts need to be granted the role - 'Cloud KMS CryptoKey Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - - 1. Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - - Required to protect the function's image. - 2. Google Storage service account - (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - - Required to protect the function's source code. If this - service account does not exist, deploying a function - without a KMS key or retrieving the service agent name - provisions it. For more information, see - https://cloud.google.com/storage/docs/projects#service-agents - and - https://cloud.google.com/storage/docs/getting-service-agent#gsutil. - - Google Cloud Functions delegates access to service agents to - protect function resources in internal projects that are not - accessible by the end user. - build_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. - build_id (str): - Output only. The Cloud Build ID of the latest - successful deployment of the function. - build_name (str): - Output only. The Cloud Build Name of the function - deployment. - ``projects//locations//builds/``. - secret_environment_variables (MutableSequence[google.cloud.functions_v1.types.SecretEnvVar]): - Secret environment variables configuration. - secret_volumes (MutableSequence[google.cloud.functions_v1.types.SecretVolume]): - Secret volumes configuration. - source_token (str): - Input only. An identifier for Firebase - function sources. Disclaimer: This field is only - supported for Firebase function deployments. - docker_repository (str): - User-managed repository created in Artifact Registry to - which the function's Docker image will be pushed after it is - built by Cloud Build. May optionally be encrypted with a - customer-managed encryption key (CMEK). If unspecified and - ``docker_registry`` is not explicitly set to - ``CONTAINER_REGISTRY``, GCF will create and use a default - Artifact Registry repository named 'gcf-artifacts' in the - 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'. - docker_registry (google.cloud.functions_v1.types.CloudFunction.DockerRegistry): - Docker Registry to use for this deployment. - - If unspecified, it defaults to ``ARTIFACT_REGISTRY``. If - ``docker_repository`` field is specified, this field should - either be left unspecified or set to ``ARTIFACT_REGISTRY``. - automatic_update_policy (google.cloud.functions_v1.types.CloudFunction.AutomaticUpdatePolicy): - - This field is a member of `oneof`_ ``runtime_update_policy``. - on_deploy_update_policy (google.cloud.functions_v1.types.CloudFunction.OnDeployUpdatePolicy): - - This field is a member of `oneof`_ ``runtime_update_policy``. - build_service_account (str): - A service account the user provides for use with Cloud - Build. The format of this field is - ``projects/{projectId}/serviceAccounts/{serviceAccountEmail}``. - """ - 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. - - Values: - VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED (0): - Unspecified. - PRIVATE_RANGES_ONLY (1): - Use the VPC Access Connector only for private - IP space from RFC1918. - ALL_TRAFFIC (2): - Force the use of VPC Access Connector for all - egress traffic from the function. - """ - 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. - - Values: - INGRESS_SETTINGS_UNSPECIFIED (0): - Unspecified. - ALLOW_ALL (1): - Allow HTTP traffic from public and private - sources. - ALLOW_INTERNAL_ONLY (2): - Allow HTTP traffic from only private VPC - sources. - ALLOW_INTERNAL_AND_GCLB (3): - Allow HTTP traffic from private VPC sources - and through GCLB. - """ - INGRESS_SETTINGS_UNSPECIFIED = 0 - ALLOW_ALL = 1 - ALLOW_INTERNAL_ONLY = 2 - ALLOW_INTERNAL_AND_GCLB = 3 - - class DockerRegistry(proto.Enum): - r"""Docker Registry to use for storing function Docker images. - - Values: - DOCKER_REGISTRY_UNSPECIFIED (0): - Unspecified. - CONTAINER_REGISTRY (1): - Docker images will be stored in multi-regional Container - Registry repositories named ``gcf``. - ARTIFACT_REGISTRY (2): - Docker images will be stored in regional Artifact Registry - repositories. By default, GCF will create and use - repositories named ``gcf-artifacts`` in every region in - which a function is deployed. But the repository to use can - also be specified by the user using the - ``docker_repository`` field. - """ - DOCKER_REGISTRY_UNSPECIFIED = 0 - CONTAINER_REGISTRY = 1 - ARTIFACT_REGISTRY = 2 - - class AutomaticUpdatePolicy(proto.Message): - r"""Security patches are applied automatically to the runtime - without requiring the function to be redeployed. - - """ - - class OnDeployUpdatePolicy(proto.Message): - r"""Security patches are only applied when a function is - redeployed. - - Attributes: - runtime_version (str): - Output only. Contains the runtime version - which was used during latest function - deployment. - """ - - runtime_version: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - source_archive_url: str = proto.Field( - proto.STRING, - number=3, - oneof='source_code', - ) - source_repository: 'SourceRepository' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source_code', - message='SourceRepository', - ) - source_upload_url: str = proto.Field( - proto.STRING, - number=16, - oneof='source_code', - ) - https_trigger: 'HttpsTrigger' = proto.Field( - proto.MESSAGE, - number=5, - oneof='trigger', - message='HttpsTrigger', - ) - event_trigger: 'EventTrigger' = proto.Field( - proto.MESSAGE, - number=6, - oneof='trigger', - message='EventTrigger', - ) - status: 'CloudFunctionStatus' = proto.Field( - proto.ENUM, - number=7, - enum='CloudFunctionStatus', - ) - entry_point: str = proto.Field( - proto.STRING, - number=8, - ) - runtime: str = proto.Field( - proto.STRING, - number=19, - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - available_memory_mb: int = proto.Field( - proto.INT32, - number=10, - ) - service_account_email: str = proto.Field( - proto.STRING, - number=11, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - version_id: int = proto.Field( - proto.INT64, - number=14, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - environment_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=17, - ) - build_environment_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=28, - ) - network: str = proto.Field( - proto.STRING, - number=18, - ) - max_instances: int = proto.Field( - proto.INT32, - number=20, - ) - min_instances: int = proto.Field( - proto.INT32, - number=32, - ) - vpc_connector: str = proto.Field( - proto.STRING, - number=22, - ) - vpc_connector_egress_settings: VpcConnectorEgressSettings = proto.Field( - proto.ENUM, - number=23, - enum=VpcConnectorEgressSettings, - ) - ingress_settings: IngressSettings = proto.Field( - proto.ENUM, - number=24, - enum=IngressSettings, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=25, - ) - build_worker_pool: str = proto.Field( - proto.STRING, - number=26, - ) - build_id: str = proto.Field( - proto.STRING, - number=27, - ) - build_name: str = proto.Field( - proto.STRING, - number=33, - ) - secret_environment_variables: MutableSequence['SecretEnvVar'] = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='SecretEnvVar', - ) - secret_volumes: MutableSequence['SecretVolume'] = proto.RepeatedField( - proto.MESSAGE, - number=30, - message='SecretVolume', - ) - source_token: str = proto.Field( - proto.STRING, - number=31, - ) - docker_repository: str = proto.Field( - proto.STRING, - number=34, - ) - docker_registry: DockerRegistry = proto.Field( - proto.ENUM, - number=35, - enum=DockerRegistry, - ) - automatic_update_policy: AutomaticUpdatePolicy = proto.Field( - proto.MESSAGE, - number=40, - oneof='runtime_update_policy', - message=AutomaticUpdatePolicy, - ) - on_deploy_update_policy: OnDeployUpdatePolicy = proto.Field( - proto.MESSAGE, - number=41, - oneof='runtime_update_policy', - message=OnDeployUpdatePolicy, - ) - build_service_account: str = proto.Field( - proto.STRING, - number=43, - ) - - -class SourceRepository(proto.Message): - r"""Describes SourceRepository, used to represent parameters - related to source repository where a function is hosted. - - Attributes: - url (str): - The URL pointing to the hosted repository where the function - is defined. There are supported Cloud Source Repository URLs - in the following formats: - - To refer to a specific commit: - ``https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/*`` - To refer to a moveable alias (branch): - ``https://source.developers.google.com/projects/*/repos/*/moveable-aliases/*/paths/*`` - In particular, to refer to HEAD use ``master`` moveable - alias. To refer to a specific fixed alias (tag): - ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` - - You may omit ``paths/*`` if you want to use the main - directory. The function response may add an empty - ``/paths/`` to the URL. - deployed_url (str): - Output only. The URL pointing to the hosted - repository where the function were defined at - the time of deployment. It always points to a - specific commit in the format described above. - """ - - url: str = proto.Field( - proto.STRING, - number=1, - ) - deployed_url: str = proto.Field( - proto.STRING, - number=2, - ) - - -class HttpsTrigger(proto.Message): - r"""Describes HttpsTrigger, could be used to connect web hooks to - function. - - Attributes: - url (str): - Output only. The deployed url for the - function. - security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): - The security level for the function. - """ - class SecurityLevel(proto.Enum): - r"""Available security level settings. - - This controls the methods to enforce security (HTTPS) on a URL. - - If unspecified, SECURE_OPTIONAL will be used. - - Values: - SECURITY_LEVEL_UNSPECIFIED (0): - Unspecified. - SECURE_ALWAYS (1): - Requests for a URL that match this handler - that do not use HTTPS are automatically - redirected to the HTTPS URL with the same path. - Query parameters are reserved for the redirect. - SECURE_OPTIONAL (2): - Both HTTP and HTTPS requests with URLs that - match the handler succeed without redirects. The - application can examine the request to determine - which protocol was used and respond accordingly. - """ - SECURITY_LEVEL_UNSPECIFIED = 0 - SECURE_ALWAYS = 1 - SECURE_OPTIONAL = 2 - - url: str = proto.Field( - proto.STRING, - number=1, - ) - security_level: SecurityLevel = proto.Field( - proto.ENUM, - number=2, - enum=SecurityLevel, - ) - - -class EventTrigger(proto.Message): - r"""Describes EventTrigger, used to request events be sent from - another service. - - Attributes: - event_type (str): - Required. The type of event to observe. For example: - ``providers/cloud.storage/eventTypes/object.change`` and - ``providers/cloud.pubsub/eventTypes/topic.publish``. - - Event types match pattern ``providers/*/eventTypes/*.*``. - The pattern contains: - - 1. namespace: For example, ``cloud.storage`` and - ``google.firebase.analytics``. - 2. resource type: The type of resource on which event - occurs. For example, the Google Cloud Storage API - includes the type ``object``. - 3. action: The action that generates the event. For example, - action for a Google Cloud Storage Object is 'change'. - These parts are lower case. - resource (str): - Required. The resource(s) from which to observe events, for - example, ``projects/_/buckets/myBucket``. - - Not all syntactically correct values are accepted by all - services. For example: - - 1. The authorization model must support it. Google Cloud - Functions only allows EventTriggers to be deployed that - observe resources in the same project as the - ``CloudFunction``. - 2. The resource type must match the pattern expected for an - ``event_type``. For example, an ``EventTrigger`` that has - an ``event_type`` of "google.pubsub.topic.publish" should - have a resource that matches Google Cloud Pub/Sub topics. - - Additionally, some services may support short names when - creating an ``EventTrigger``. These will always be returned - in the normalized "long" format. - - See each *service's* documentation for supported formats. - service (str): - The hostname of the service that should be observed. - - If no string is provided, the default service implementing - the API will be used. For example, - ``storage.googleapis.com`` is the default for all event - types in the ``google.storage`` namespace. - failure_policy (google.cloud.functions_v1.types.FailurePolicy): - Specifies policy for failed executions. - """ - - event_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource: str = proto.Field( - proto.STRING, - number=2, - ) - service: str = proto.Field( - proto.STRING, - number=3, - ) - failure_policy: 'FailurePolicy' = proto.Field( - proto.MESSAGE, - number=5, - message='FailurePolicy', - ) - - -class FailurePolicy(proto.Message): - r"""Describes the policy in case of function's execution failure. - If empty, then defaults to ignoring failures (i.e. not retrying - them). - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - retry (google.cloud.functions_v1.types.FailurePolicy.Retry): - If specified, then the function will be - retried in case of a failure. - - This field is a member of `oneof`_ ``action``. - """ - - class Retry(proto.Message): - r"""Describes the retry policy in case of function's execution - failure. A function execution will be retried on any failure. A - failed execution will be retried up to 7 days with an - exponential backoff (capped at 10 seconds). - Retried execution is charged as any other execution. - - """ - - retry: Retry = proto.Field( - proto.MESSAGE, - number=1, - oneof='action', - message=Retry, - ) - - -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 (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of 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: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - secret: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = 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. Secret value is not a part of the - configuration. Every filesystem read operation performs a lookup - in secret manager to retrieve the secret value. - - 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 paths: /etc/secrets Restricted mount - paths: /cloudsql, /dev/log, /pod, /proc, /var/log - project_id (str): - Project identifier (preferrably project - number but can also be the project ID) of the - project that contains the secret. If not set, it - will be populated with the function's project - assuming that the secret exists in the same - project as of the function. - secret (str): - Name of the secret in secret manager (not the - full resource name). - versions (MutableSequence[google.cloud.functions_v1.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: str = proto.Field( - proto.STRING, - number=1, - ) - path: str = proto.Field( - proto.STRING, - number=2, - ) - - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - secret: str = proto.Field( - proto.STRING, - number=3, - ) - versions: MutableSequence[SecretVersion] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SecretVersion, - ) - - -class CreateFunctionRequest(proto.Message): - r"""Request for the ``CreateFunction`` method. - - Attributes: - location (str): - Required. The project and location in which the function - should be created, specified in the format - ``projects/*/locations/*`` - function (google.cloud.functions_v1.types.CloudFunction): - Required. Function to be created. - """ - - location: str = proto.Field( - proto.STRING, - number=1, - ) - function: 'CloudFunction' = proto.Field( - proto.MESSAGE, - number=2, - message='CloudFunction', - ) - - -class UpdateFunctionRequest(proto.Message): - r"""Request for the ``UpdateFunction`` method. - - Attributes: - function (google.cloud.functions_v1.types.CloudFunction): - Required. New version of the function. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields in ``CloudFunction`` that have - to be updated. - """ - - function: 'CloudFunction' = proto.Field( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetFunctionRequest(proto.Message): - r"""Request for the ``GetFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - details should be obtained. - version_id (int): - Optional. The optional version of the - function whose details should be obtained. The - version of a 1st Gen function is an integer that - starts from 1 and gets incremented on - redeployments. Each deployment creates a config - version of the underlying function. GCF may keep - historical configs for old versions. This field - can be specified to fetch the historical - configs. Leave it blank or set to 0 to get the - latest version of the function. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - version_id: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListFunctionsRequest(proto.Message): - r"""Request for the ``ListFunctions`` method. - - Attributes: - parent (str): - 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. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListFunctionsResponse(proto.Message): - r"""Response for the ``ListFunctions`` method. - - Attributes: - functions (MutableSequence[google.cloud.functions_v1.types.CloudFunction]): - The functions that match the request. - next_page_token (str): - If not empty, indicates that there may be more functions - that match the request; this value should be passed in a new - [google.cloud.functions.v1.ListFunctionsRequest][google.cloud.functions.v1.ListFunctionsRequest] - to get more functions. - unreachable (MutableSequence[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: MutableSequence['CloudFunction'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CloudFunction', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DeleteFunctionRequest(proto.Message): - r"""Request for the ``DeleteFunction`` method. - - Attributes: - name (str): - Required. The name of the function which - should be deleted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CallFunctionRequest(proto.Message): - r"""Request for the ``CallFunction`` method. - - Attributes: - name (str): - Required. The name of the function to be - called. - data (str): - Required. Input to be passed to the function. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CallFunctionResponse(proto.Message): - r"""Response of ``CallFunction`` method. - - Attributes: - execution_id (str): - Execution id of function invocation. - result (str): - Result populated for successful execution of - synchronous function. Will not be populated if - function does not return a result through - context. - error (str): - Either system or user-function generated - error. Set if execution was not successful. - """ - - execution_id: str = proto.Field( - proto.STRING, - number=1, - ) - result: str = proto.Field( - proto.STRING, - number=2, - ) - error: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GenerateUploadUrlRequest(proto.Message): - r"""Request of ``GenerateSourceUploadUrl`` method. - - Attributes: - parent (str): - The project and location in which the Google Cloud Storage - signed URL should be generated, specified in the format - ``projects/*/locations/*``. - kms_key_name (str): - Resource name of a KMS crypto key (managed by the user) used - to encrypt/decrypt function source code objects in - intermediate Cloud Storage buckets. When you generate an - upload url and upload your source code, it gets copied to an - intermediate Cloud Storage bucket. The source code is then - copied to a versioned directory in the sources bucket in the - consumer project during the function deployment. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - The Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - must be granted the role 'Cloud KMS CryptoKey - Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - GCF will delegate access to the Google Storage service - account in the internal project. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -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. - """ - - upload_url: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateDownloadUrlRequest(proto.Message): - r"""Request of ``GenerateDownloadUrl`` method. - - Attributes: - name (str): - The name of function for which source code - Google Cloud Storage signed URL should be - generated. - version_id (int): - The optional version of function. If not set, - default, current version is used. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - version_id: int = proto.Field( - proto.UINT64, - number=2, - ) - - -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: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/operations.py b/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/operations.py deleted file mode 100644 index 199377362d65..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/google/cloud/functions_v1/types/operations.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.functions.v1', - manifest={ - 'OperationType', - 'OperationMetadataV1', - }, -) - - -class OperationType(proto.Enum): - r"""A type of an operation. - - Values: - OPERATION_UNSPECIFIED (0): - Unknown operation type. - CREATE_FUNCTION (1): - Triggered by CreateFunction call - UPDATE_FUNCTION (2): - Triggered by UpdateFunction call - DELETE_FUNCTION (3): - Triggered by DeleteFunction call. - """ - OPERATION_UNSPECIFIED = 0 - CREATE_FUNCTION = 1 - UPDATE_FUNCTION = 2 - DELETE_FUNCTION = 3 - - -class OperationMetadataV1(proto.Message): - r"""Metadata describing an [Operation][google.longrunning.Operation] - - Attributes: - target (str): - Target of the operation - for example - ``projects/project-1/locations/region-1/functions/function-1`` - type_ (google.cloud.functions_v1.types.OperationType): - Type of operation. - request (google.protobuf.any_pb2.Any): - The original request that started the - operation. - version_id (int): - Version id of the function created or updated - by an API call. This field is only populated for - Create and Update operations. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of the operation. - build_id (str): - The Cloud Build ID of the function created or - updated by an API call. This field is only - populated for Create and Update operations. - source_token (str): - An identifier for Firebase function sources. - Disclaimer: This field is only supported for - Firebase function deployments. - build_name (str): - The Cloud Build Name of the function deployment. This field - is only populated for Create and Update operations. - ``projects//locations//builds/``. - """ - - target: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'OperationType' = proto.Field( - proto.ENUM, - number=2, - enum='OperationType', - ) - request: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=3, - message=any_pb2.Any, - ) - version_id: int = proto.Field( - proto.INT64, - number=4, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - build_id: str = proto.Field( - proto.STRING, - number=6, - ) - source_token: str = proto.Field( - proto.STRING, - number=7, - ) - build_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-functions/v1/mypy.ini b/owl-bot-staging/google-cloud-functions/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-functions/v1/noxfile.py b/owl-bot-staging/google-cloud-functions/v1/noxfile.py deleted file mode 100644 index ded0fb5e5eba..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-functions' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - 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", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py deleted file mode 100644 index fca8c1ef9a8c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 CallFunction -# 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_v1_generated_CloudFunctionsService_CallFunction_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = await client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py deleted file mode 100644 index b2a2b55db113..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 CallFunction -# 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_v1_generated_CloudFunctionsService_CallFunction_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_call_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.CallFunctionRequest( - name="name_value", - data="data_value", - ) - - # Make the request - response = client.call_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py deleted file mode 100644 index 8b7dea06b305..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_CreateFunction_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # 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_v1_generated_CloudFunctionsService_CreateFunction_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py deleted file mode 100644 index c778ea6ffaca..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_CreateFunction_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_create_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.CreateFunctionRequest( - location="location_value", - function=function, - ) - - # 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_v1_generated_CloudFunctionsService_CreateFunction_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py deleted file mode 100644 index 0b342415a2f7..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_DeleteFunction_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.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_v1_generated_CloudFunctionsService_DeleteFunction_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py deleted file mode 100644 index 7bdb97e084b8..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_DeleteFunction_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_delete_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.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_v1_generated_CloudFunctionsService_DeleteFunction_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py deleted file mode 100644 index 9d5a1d65181b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = await client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py deleted file mode 100644 index c967bc9522f3..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_generate_download_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateDownloadUrlRequest( - ) - - # Make the request - response = client.generate_download_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py deleted file mode 100644 index 5983264423b2..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = await client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py deleted file mode 100644 index 7738b0721312..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_generate_upload_url(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GenerateUploadUrlRequest( - ) - - # Make the request - response = client.generate_upload_url(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py deleted file mode 100644 index 337e79b61887..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GetFunction_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py deleted file mode 100644 index 62fa95e9fb40..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_GetFunction_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_get_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.GetFunctionRequest( - name="name_value", - ) - - # Make the request - response = client.get_function(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py deleted file mode 100644 index e04f2a2b0441..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py deleted file mode 100644 index 44daf212d98f..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py deleted file mode 100644 index c4414046e281..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_ListFunctions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py deleted file mode 100644 index 5522599cc8ef..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_ListFunctions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_list_functions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = functions_v1.ListFunctionsRequest( - ) - - # Make the request - page_result = client.list_functions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py deleted file mode 100644 index b123bbfce5c0..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py deleted file mode 100644 index 5b1c0844378c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py deleted file mode 100644 index 6dc5ecc362f9..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py deleted file mode 100644 index e65c7a688c8b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-functions - - -# [START cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py deleted file mode 100644 index 1a3b2fbbbf67..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_UpdateFunction_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -async def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceAsyncClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # 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_v1_generated_CloudFunctionsService_UpdateFunction_async] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py deleted file mode 100644 index be90cdde19c6..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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_v1_generated_CloudFunctionsService_UpdateFunction_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import functions_v1 - - -def sample_update_function(): - # Create a client - client = functions_v1.CloudFunctionsServiceClient() - - # Initialize request argument(s) - function = functions_v1.CloudFunction() - function.source_archive_url = "source_archive_url_value" - - request = functions_v1.UpdateFunctionRequest( - function=function, - ) - - # 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_v1_generated_CloudFunctionsService_UpdateFunction_sync] diff --git a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json b/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json deleted file mode 100644 index 3a16e5fca57c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json +++ /dev/null @@ -1,1754 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.functions.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-functions", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "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_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.call_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CallFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CallFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CallFunctionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "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_v1.types.CallFunctionResponse", - "shortName": "call_function" - }, - "description": "Sample for CallFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CallFunction_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_call_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "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_v1_generated_cloud_functions_service_create_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.create_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.CreateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "CreateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.CreateFunctionRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "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_v1_generated_cloud_functions_service_create_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_CreateFunction_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_create_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1_generated_cloud_functions_service_delete_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.delete_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.DeleteFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "DeleteFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1_generated_cloud_functions_service_delete_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_DeleteFunction_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_delete_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_download_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateDownloadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateDownloadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.GenerateDownloadUrlResponse", - "shortName": "generate_download_url" - }, - "description": "Sample for GenerateDownloadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_download_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.generate_upload_url", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GenerateUploadUrl" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.GenerateUploadUrlResponse", - "shortName": "generate_upload_url" - }, - "description": "Sample for GenerateUploadUrl", - "file": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GenerateUploadUrl_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_generate_upload_url_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.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_v1.types.CloudFunction", - "shortName": "get_function" - }, - "description": "Sample for GetFunction", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetFunction_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_function_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.get_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.GetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsAsyncPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.list_functions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.ListFunctions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "ListFunctions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.ListFunctionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.functions_v1.services.cloud_functions_service.pagers.ListFunctionsPager", - "shortName": "list_functions" - }, - "description": "Sample for ListFunctions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_ListFunctions_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_list_functions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.set_iam_policy", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.TestIamPermissions", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient", - "shortName": "CloudFunctionsServiceAsyncClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceAsyncClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "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_v1_generated_cloud_functions_service_update_function_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient", - "shortName": "CloudFunctionsServiceClient" - }, - "fullName": "google.cloud.functions_v1.CloudFunctionsServiceClient.update_function", - "method": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction", - "service": { - "fullName": "google.cloud.functions.v1.CloudFunctionsService", - "shortName": "CloudFunctionsService" - }, - "shortName": "UpdateFunction" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.functions_v1.types.UpdateFunctionRequest" - }, - { - "name": "function", - "type": "google.cloud.functions_v1.types.CloudFunction" - }, - { - "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_v1_generated_cloud_functions_service_update_function_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudfunctions_v1_generated_CloudFunctionsService_UpdateFunction_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v1_generated_cloud_functions_service_update_function_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-functions/v1/scripts/fixup_functions_v1_keywords.py b/owl-bot-staging/google-cloud-functions/v1/scripts/fixup_functions_v1_keywords.py deleted file mode 100644 index ac10d40edbcd..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/scripts/fixup_functions_v1_keywords.py +++ /dev/null @@ -1,186 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 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]] = { - 'call_function': ('name', 'data', ), - 'create_function': ('location', 'function', ), - 'delete_function': ('name', ), - 'generate_download_url': ('name', 'version_id', ), - 'generate_upload_url': ('parent', 'kms_key_name', ), - 'get_function': ('name', 'version_id', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_functions': ('parent', 'page_size', 'page_token', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - '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/owl-bot-staging/google-cloud-functions/v1/setup.py b/owl-bot-staging/google-cloud-functions/v1/setup.py deleted file mode 100644 index 03ce0d0f560d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/setup.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-functions' - - -description = "Google Cloud Functions API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/functions/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.7.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 "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v1/tests/__init__.py b/owl-bot-staging/google-cloud-functions/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-functions/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/__init__.py b/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py b/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py deleted file mode 100644 index 51afed24e2ab..000000000000 --- a/owl-bot-staging/google-cloud-functions/v1/tests/unit/gapic/functions_v1/test_cloud_functions_service.py +++ /dev/null @@ -1,8527 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient -from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient -from google.cloud.functions_v1.services.cloud_functions_service import pagers -from google.cloud.functions_v1.services.cloud_functions_service import transports -from google.cloud.functions_v1.types import functions -from google.cloud.functions_v1.types import operations -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 # type: ignore -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -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.type import expr_pb2 # type: ignore -import google.auth - - -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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 CloudFunctionsServiceClient._get_default_mtls_endpoint(None) is None - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CloudFunctionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - CloudFunctionsServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - CloudFunctionsServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert CloudFunctionsServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert CloudFunctionsServiceClient._get_client_cert_source(None, False) is None - assert CloudFunctionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert CloudFunctionsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert CloudFunctionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert CloudFunctionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(CloudFunctionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert CloudFunctionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert CloudFunctionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CloudFunctionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert CloudFunctionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CloudFunctionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == CloudFunctionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CloudFunctionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert CloudFunctionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - CloudFunctionsServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert CloudFunctionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert CloudFunctionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert CloudFunctionsServiceClient._get_universe_domain(None, None) == CloudFunctionsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - CloudFunctionsServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), - (CloudFunctionsServiceClient, "rest"), -]) -def test_cloud_functions_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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudfunctions.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CloudFunctionsServiceRestTransport, "rest"), -]) -def test_cloud_functions_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", [ - (CloudFunctionsServiceClient, "grpc"), - (CloudFunctionsServiceAsyncClient, "grpc_asyncio"), - (CloudFunctionsServiceClient, "rest"), -]) -def test_cloud_functions_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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudfunctions.googleapis.com' - ) - - -def test_cloud_functions_service_client_get_transport_class(): - transport = CloudFunctionsServiceClient.get_transport_class() - available_transports = [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceRestTransport, - ] - assert transport in available_transports - - transport = CloudFunctionsServiceClient.get_transport_class("grpc") - assert transport == transports.CloudFunctionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_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(CloudFunctionsServiceClient, '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(CloudFunctionsServiceClient, '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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "true"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", "false"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest", "true"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CloudFunctionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_cloud_functions_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient -]) -@mock.patch.object(CloudFunctionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - CloudFunctionsServiceClient, CloudFunctionsServiceAsyncClient -]) -@mock.patch.object(CloudFunctionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceClient)) -@mock.patch.object(CloudFunctionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CloudFunctionsServiceAsyncClient)) -def test_cloud_functions_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = CloudFunctionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = CloudFunctionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc"), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest"), -]) -def test_cloud_functions_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceRestTransport, "rest", None), -]) -def test_cloud_functions_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_cloud_functions_service_client_client_options_from_dict(): - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CloudFunctionsServiceClient( - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport, "grpc", grpc_helpers), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_cloud_functions_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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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.ListFunctionsRequest, - dict, -]) -def test_list_functions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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] - request = functions.ListFunctionsRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_functions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - -def test_list_functions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.ListFunctionsRequest( - parent='parent_value', - page_token='page_token_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_functions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_functions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_functions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_functions] = mock_rpc - request = {} - client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_functions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - -@pytest.mark.asyncio -async def test_list_functions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_functions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_functions] = mock_object - - request = {} - await client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_functions_async(transport: str = 'grpc_asyncio', request_type=functions.ListFunctionsRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.ListFunctionsRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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_pager(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_functions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.CloudFunction) - for i in results) -def test_list_functions_pages(transport_name: str = "grpc"): - client = CloudFunctionsServiceClient( - 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.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - 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 = CloudFunctionsServiceAsyncClient( - 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.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - 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.CloudFunction) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_functions_async_pages(): - client = CloudFunctionsServiceAsyncClient( - 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.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_functions(request={}) - ).pages: - 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.GetFunctionRequest, - dict, -]) -def test_get_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - build_service_account='build_service_account_value', - source_archive_url='source_archive_url_value', - ) - 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] - request = functions.GetFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - assert response.build_service_account == 'build_service_account_value' - - -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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - -def test_get_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GetFunctionRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest( - name='name_value', - ) - -def test_get_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_function] = mock_rpc - request = {} - client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - build_service_account='build_service_account_value', - )) - response = await 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_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_function] = mock_object - - request = {} - await client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_function_async(transport: str = 'grpc_asyncio', request_type=functions.GetFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - 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.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - build_service_account='build_service_account_value', - )) - 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] - request = functions.GetFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - assert response.build_service_account == 'build_service_account_value' - - -@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 = CloudFunctionsServiceClient( - 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.CloudFunction() - 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 = CloudFunctionsServiceAsyncClient( - 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.CloudFunction()) - 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 = CloudFunctionsServiceClient( - 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.CloudFunction() - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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.CloudFunction() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CloudFunction()) - # 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 = CloudFunctionsServiceAsyncClient( - 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.CreateFunctionRequest, - dict, -]) -def test_create_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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] - request = functions.CreateFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - -def test_create_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.CreateFunctionRequest( - location='location_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest( - location='location_value', - ) - -def test_create_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_function] = mock_rpc - request = {} - client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - -@pytest.mark.asyncio -async def test_create_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_function] = mock_object - - request = {} - await client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_function_async(transport: str = 'grpc_asyncio', request_type=functions.CreateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.CreateFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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.location = 'location_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', - 'location=location_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - 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.location = 'location_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', - 'location=location_value', - ) in kw['metadata'] - - -def test_create_function_flattened(): - client = CloudFunctionsServiceClient( - 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( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_create_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - 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( - location='location_value', - function=functions.CloudFunction(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].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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] - request = functions.UpdateFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - -def test_update_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.UpdateFunctionRequest( - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest( - ) - -def test_update_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_function] = mock_rpc - request = {} - client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - -@pytest.mark.asyncio -async def test_update_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_function] = mock_object - - request = {} - await client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_function_async(transport: str = 'grpc_asyncio', request_type=functions.UpdateFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.UpdateFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - - -def test_update_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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.CloudFunction(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - 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.CloudFunction(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].function - mock_val = functions.CloudFunction(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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.CloudFunction(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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] - request = functions.DeleteFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - -def test_delete_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.DeleteFunctionRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest( - name='name_value', - ) - -def test_delete_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_function] = mock_rpc - request = {} - client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - -@pytest.mark.asyncio -async def test_delete_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_function] = mock_object - - request = {} - await client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_function_async(transport: str = 'grpc_asyncio', request_type=functions.DeleteFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.DeleteFunctionRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceAsyncClient( - 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.CallFunctionRequest, - dict, -]) -def test_call_function(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - ) - response = client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = functions.CallFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -def test_call_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 = CloudFunctionsServiceClient( - 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.call_function), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.call_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - - -def test_call_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.CallFunctionRequest( - name='name_value', - data='data_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.call_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest( - name='name_value', - data='data_value', - ) - -def test_call_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.call_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.call_function] = mock_rpc - request = {} - client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.call_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_call_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - )) - response = await client.call_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CallFunctionRequest() - -@pytest.mark.asyncio -async def test_call_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.call_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.call_function] = mock_object - - request = {} - await client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.call_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_call_function_async(transport: str = 'grpc_asyncio', request_type=functions.CallFunctionRequest): - client = CloudFunctionsServiceAsyncClient( - 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.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - )) - response = await client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = functions.CallFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_call_function_async_from_dict(): - await test_call_function_async(request_type=dict) - - -def test_call_function_field_headers(): - client = CloudFunctionsServiceClient( - 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.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = functions.CallFunctionResponse() - client.call_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_call_function_field_headers_async(): - client = CloudFunctionsServiceAsyncClient( - 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.CallFunctionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - await client.call_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_call_function_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - - -def test_call_function_flattened_error(): - client = CloudFunctionsServiceClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - -@pytest.mark.asyncio -async def test_call_function_flattened_async(): - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.call_function), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = functions.CallFunctionResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(functions.CallFunctionResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.call_function( - name='name_value', - data='data_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 - arg = args[0].data - mock_val = 'data_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_call_function_flattened_error_async(): - client = CloudFunctionsServiceAsyncClient( - 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.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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] - request = functions.GenerateUploadUrlRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_upload_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - -def test_generate_upload_url_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GenerateUploadUrlRequest( - parent='parent_value', - kms_key_name='kms_key_name_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_upload_url(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest( - parent='parent_value', - kms_key_name='kms_key_name_value', - ) - -def test_generate_upload_url_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_upload_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_upload_url] = mock_rpc - request = {} - client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_upload_url_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_upload_url_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_upload_url in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.generate_upload_url] = mock_object - - request = {} - await client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_upload_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateUploadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.GenerateUploadUrlRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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] - request = functions.GenerateDownloadUrlRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_download_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - -def test_generate_download_url_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GenerateDownloadUrlRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_download_url(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest( - name='name_value', - ) - -def test_generate_download_url_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_download_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_download_url] = mock_rpc - request = {} - client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_download_url_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_download_url_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_download_url in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.generate_download_url] = mock_object - - request = {} - await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_download_url_async(transport: str = 'grpc_asyncio', request_type=functions.GenerateDownloadUrlRequest): - client = CloudFunctionsServiceAsyncClient( - 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] - request = functions.GenerateDownloadUrlRequest() - assert args[0] == request - - # 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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.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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_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 = CloudFunctionsServiceClient( - 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.set_iam_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = CloudFunctionsServiceAsyncClient( - 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.set_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.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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) - _, 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_foreign(): - client = CloudFunctionsServiceClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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_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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_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 = CloudFunctionsServiceClient( - 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_iam_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = CloudFunctionsServiceAsyncClient( - 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_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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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_foreign(): - client = CloudFunctionsServiceClient( - 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.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = CloudFunctionsServiceClient( - 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.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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_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 = CloudFunctionsServiceClient( - 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.test_iam_permissions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = CloudFunctionsServiceAsyncClient( - 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.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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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_foreign(): - client = CloudFunctionsServiceClient( - 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.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.ListFunctionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_functions(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_functions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_functions] = mock_rpc - - request = {} - client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_functions_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_list_functions") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_list_functions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.ListFunctionsRequest.pb(functions.ListFunctionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.ListFunctionsResponse.to_json(functions.ListFunctionsResponse()) - - request = functions.ListFunctionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.ListFunctionsResponse() - - client.list_functions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_functions_rest_bad_request(transport: str = 'rest', request_type=functions.ListFunctionsRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_functions(request) - - -def test_list_functions_rest_pager(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - functions.CloudFunction(), - ], - next_page_token='abc', - ), - functions.ListFunctionsResponse( - functions=[], - next_page_token='def', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - ], - next_page_token='ghi', - ), - functions.ListFunctionsResponse( - functions=[ - functions.CloudFunction(), - functions.CloudFunction(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(functions.ListFunctionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_functions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.CloudFunction) - for i in results) - - pages = list(client.list_functions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.CloudFunction( - name='name_value', - description='description_value', - status=functions.CloudFunctionStatus.ACTIVE, - entry_point='entry_point_value', - runtime='runtime_value', - available_memory_mb=1991, - service_account_email='service_account_email_value', - version_id=1074, - network='network_value', - max_instances=1389, - min_instances=1387, - vpc_connector='vpc_connector_value', - vpc_connector_egress_settings=functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY, - ingress_settings=functions.CloudFunction.IngressSettings.ALLOW_ALL, - kms_key_name='kms_key_name_value', - build_worker_pool='build_worker_pool_value', - build_id='build_id_value', - build_name='build_name_value', - source_token='source_token_value', - docker_repository='docker_repository_value', - docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, - build_service_account='build_service_account_value', - source_archive_url='source_archive_url_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.CloudFunction.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_function(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CloudFunction) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.status == functions.CloudFunctionStatus.ACTIVE - assert response.entry_point == 'entry_point_value' - assert response.runtime == 'runtime_value' - assert response.available_memory_mb == 1991 - assert response.service_account_email == 'service_account_email_value' - assert response.version_id == 1074 - assert response.network == 'network_value' - assert response.max_instances == 1389 - assert response.min_instances == 1387 - assert response.vpc_connector == 'vpc_connector_value' - assert response.vpc_connector_egress_settings == functions.CloudFunction.VpcConnectorEgressSettings.PRIVATE_RANGES_ONLY - assert response.ingress_settings == functions.CloudFunction.IngressSettings.ALLOW_ALL - assert response.kms_key_name == 'kms_key_name_value' - assert response.build_worker_pool == 'build_worker_pool_value' - assert response.build_id == 'build_id_value' - assert response.build_name == 'build_name_value' - assert response.source_token == 'source_token_value' - assert response.docker_repository == 'docker_repository_value' - assert response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY - assert response.build_service_account == 'build_service_account_value' - -def test_get_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_function] = mock_rpc - - request = {} - client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_function_rest_required_fields(request_type=functions.GetFunctionRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_function._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("version_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.CloudFunction() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.CloudFunction.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_function_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(("versionId", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_function_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_get_function") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_get_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GetFunctionRequest.pb(functions.GetFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.CloudFunction.to_json(functions.CloudFunction()) - - request = functions.GetFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.CloudFunction() - - client.get_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_function_rest_bad_request(transport: str = 'rest', request_type=functions.GetFunctionRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_function(request) - - -def test_get_function_rest_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.CloudFunction() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.CloudFunction.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_get_function_rest_flattened_error(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_function( - functions.GetFunctionRequest(), - name='name_value', - ) - - -def test_get_function_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'location': 'projects/sample1/locations/sample2'} - request_init["function"] = {'name': 'name_value', 'description': 'description_value', 'source_archive_url': 'source_archive_url_value', 'source_repository': {'url': 'url_value', 'deployed_url': 'deployed_url_value'}, 'source_upload_url': 'source_upload_url_value', 'https_trigger': {'url': 'url_value', 'security_level': 1}, 'event_trigger': {'event_type': 'event_type_value', 'resource': 'resource_value', 'service': 'service_value', 'failure_policy': {'retry': {}}}, 'status': 1, 'entry_point': 'entry_point_value', 'runtime': 'runtime_value', 'timeout': {'seconds': 751, 'nanos': 543}, 'available_memory_mb': 1991, 'service_account_email': 'service_account_email_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'version_id': 1074, 'labels': {}, 'environment_variables': {}, 'build_environment_variables': {}, 'network': 'network_value', 'max_instances': 1389, 'min_instances': 1387, 'vpc_connector': 'vpc_connector_value', 'vpc_connector_egress_settings': 1, 'ingress_settings': 1, 'kms_key_name': 'kms_key_name_value', 'build_worker_pool': 'build_worker_pool_value', 'build_id': 'build_id_value', 'build_name': 'build_name_value', 'secret_environment_variables': [{'key': 'key_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'version': 'version_value'}], 'secret_volumes': [{'mount_path': 'mount_path_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'versions': [{'version': 'version_value', 'path': 'path_value'}]}], 'source_token': 'source_token_value', 'docker_repository': 'docker_repository_value', 'docker_registry': 1, 'automatic_update_policy': {}, 'on_deploy_update_policy': {'runtime_version': 'runtime_version_value'}, 'build_service_account': 'build_service_account_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = functions.CreateFunctionRequest.meta.fields["function"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["function"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["function"][field])): - del request_init["function"][field][i][subfield] - else: - del request_init["function"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_function] = mock_rpc - - request = {} - client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_function_rest_required_fields(request_type=functions.CreateFunctionRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["location"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["location"] = 'location_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "location" in jsonified_request - assert jsonified_request["location"] == 'location_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_function_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("location", "function", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_function_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_create_function") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_create_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.CreateFunctionRequest.pb(functions.CreateFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.CreateFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_function_rest_bad_request(transport: str = 'rest', request_type=functions.CreateFunctionRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'location': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_function(request) - - -def test_create_function_rest_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'location': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{location=projects/*/locations/*}/functions" % client.transport._host, args[1]) - - -def test_create_function_rest_flattened_error(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_function( - functions.CreateFunctionRequest(), - location='location_value', - function=functions.CloudFunction(name='name_value'), - ) - - -def test_create_function_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - request_init["function"] = {'name': 'projects/sample1/locations/sample2/functions/sample3', 'description': 'description_value', 'source_archive_url': 'source_archive_url_value', 'source_repository': {'url': 'url_value', 'deployed_url': 'deployed_url_value'}, 'source_upload_url': 'source_upload_url_value', 'https_trigger': {'url': 'url_value', 'security_level': 1}, 'event_trigger': {'event_type': 'event_type_value', 'resource': 'resource_value', 'service': 'service_value', 'failure_policy': {'retry': {}}}, 'status': 1, 'entry_point': 'entry_point_value', 'runtime': 'runtime_value', 'timeout': {'seconds': 751, 'nanos': 543}, 'available_memory_mb': 1991, 'service_account_email': 'service_account_email_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'version_id': 1074, 'labels': {}, 'environment_variables': {}, 'build_environment_variables': {}, 'network': 'network_value', 'max_instances': 1389, 'min_instances': 1387, 'vpc_connector': 'vpc_connector_value', 'vpc_connector_egress_settings': 1, 'ingress_settings': 1, 'kms_key_name': 'kms_key_name_value', 'build_worker_pool': 'build_worker_pool_value', 'build_id': 'build_id_value', 'build_name': 'build_name_value', 'secret_environment_variables': [{'key': 'key_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'version': 'version_value'}], 'secret_volumes': [{'mount_path': 'mount_path_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'versions': [{'version': 'version_value', 'path': 'path_value'}]}], 'source_token': 'source_token_value', 'docker_repository': 'docker_repository_value', 'docker_registry': 1, 'automatic_update_policy': {}, 'on_deploy_update_policy': {'runtime_version': 'runtime_version_value'}, 'build_service_account': 'build_service_account_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = functions.UpdateFunctionRequest.meta.fields["function"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["function"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["function"][field])): - del request_init["function"][field][i][subfield] - else: - del request_init["function"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_function] = mock_rpc - - request = {} - client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_function_rest_required_fields(request_type=functions.UpdateFunctionRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_function._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_function_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("function", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_function_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_update_function") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_update_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.UpdateFunctionRequest.pb(functions.UpdateFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.UpdateFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_function_rest_bad_request(transport: str = 'rest', request_type=functions.UpdateFunctionRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_function(request) - - -def test_update_function_rest_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - function=functions.CloudFunction(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{function.name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_update_function_rest_flattened_error(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_function( - functions.UpdateFunctionRequest(), - function=functions.CloudFunction(name='name_value'), - ) - - -def test_update_function_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_function] = mock_rpc - - request = {} - client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_function_rest_required_fields(request_type=functions.DeleteFunctionRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_function_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_function_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_delete_function") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_delete_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.DeleteFunctionRequest.pb(functions.DeleteFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.DeleteFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_function_rest_bad_request(transport: str = 'rest', request_type=functions.DeleteFunctionRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_function(request) - - -def test_delete_function_rest_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_delete_function_rest_flattened_error(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - - -def test_delete_function_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.CallFunctionRequest, - dict, -]) -def test_call_function_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.CallFunctionResponse( - execution_id='execution_id_value', - result='result_value', - error='error_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.CallFunctionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.call_function(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.CallFunctionResponse) - assert response.execution_id == 'execution_id_value' - assert response.result == 'result_value' - assert response.error == 'error_value' - -def test_call_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.call_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.call_function] = mock_rpc - - request = {} - client.call_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.call_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_call_function_rest_required_fields(request_type=functions.CallFunctionRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["data"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).call_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["data"] = 'data_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).call_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "data" in jsonified_request - assert jsonified_request["data"] == 'data_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.CallFunctionResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.CallFunctionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.call_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_call_function_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.call_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "data", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_call_function_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_call_function") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_call_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.CallFunctionRequest.pb(functions.CallFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.CallFunctionResponse.to_json(functions.CallFunctionResponse()) - - request = functions.CallFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.CallFunctionResponse() - - client.call_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_call_function_rest_bad_request(transport: str = 'rest', request_type=functions.CallFunctionRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.call_function(request) - - -def test_call_function_rest_flattened(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.CallFunctionResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - data='data_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.CallFunctionResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.call_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/functions/*}:call" % client.transport._host, args[1]) - - -def test_call_function_rest_flattened_error(transport: str = 'rest'): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.call_function( - functions.CallFunctionRequest(), - name='name_value', - data='data_value', - ) - - -def test_call_function_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.GenerateUploadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_upload_url(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_upload_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_upload_url] = mock_rpc - - request = {} - client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_upload_url_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_generate_upload_url") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_generate_upload_url") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GenerateUploadUrlRequest.pb(functions.GenerateUploadUrlRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.GenerateUploadUrlResponse.to_json(functions.GenerateUploadUrlResponse()) - - request = functions.GenerateUploadUrlRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.GenerateUploadUrlResponse() - - client.generate_upload_url(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_upload_url_rest_bad_request(transport: str = 'rest', request_type=functions.GenerateUploadUrlRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_upload_url(request) - - -def test_generate_upload_url_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.GenerateDownloadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_download_url(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_download_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_download_url] = mock_rpc - - request = {} - client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_download_url_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_generate_download_url") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_generate_download_url") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GenerateDownloadUrlRequest.pb(functions.GenerateDownloadUrlRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.GenerateDownloadUrlResponse.to_json(functions.GenerateDownloadUrlResponse()) - - request = functions.GenerateDownloadUrlRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.GenerateDownloadUrlResponse() - - client.generate_download_url(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_download_url_rest_bad_request(transport: str = 'rest', request_type=functions.GenerateDownloadUrlRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_download_url(request) - - -def test_generate_download_url_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("options", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("options", )) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - -def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.CloudFunctionsServiceRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.CloudFunctionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.CloudFunctionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CloudFunctionsServiceRestInterceptor(), - ) - client = CloudFunctionsServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.CloudFunctionsServiceRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_error(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudFunctionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudFunctionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudFunctionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - transports.CloudFunctionsServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = CloudFunctionsServiceClient.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 = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudFunctionsServiceGrpcTransport, - ) - -def test_cloud_functions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_cloud_functions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.functions_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CloudFunctionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_functions', - 'get_function', - 'create_function', - 'update_function', - 'delete_function', - 'call_function', - 'generate_upload_url', - 'generate_download_url', - '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_cloud_functions_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_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport( - 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_cloud_functions_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_v1.services.cloud_functions_service.transports.CloudFunctionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudFunctionsServiceTransport() - adc.assert_called_once() - - -def test_cloud_functions_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) - CloudFunctionsServiceClient() - 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.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - ], -) -def test_cloud_functions_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.CloudFunctionsServiceGrpcTransport, - transports.CloudFunctionsServiceGrpcAsyncIOTransport, - transports.CloudFunctionsServiceRestTransport, - ], -) -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", - [ - (transports.CloudFunctionsServiceGrpcTransport, grpc_helpers), - (transports.CloudFunctionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_cloud_functions_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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_cloud_functions_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.CloudFunctionsServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_cloud_functions_service_rest_lro_client(): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_cloud_functions_service_host_no_port(transport_name): - client = CloudFunctionsServiceClient( - 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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudfunctions.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_cloud_functions_service_host_with_port(transport_name): - client = CloudFunctionsServiceClient( - 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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudfunctions.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_cloud_functions_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CloudFunctionsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CloudFunctionsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_functions._session - session2 = client2.transport.list_functions._session - assert session1 != session2 - session1 = client1.transport.get_function._session - session2 = client2.transport.get_function._session - assert session1 != session2 - session1 = client1.transport.create_function._session - session2 = client2.transport.create_function._session - assert session1 != session2 - session1 = client1.transport.update_function._session - session2 = client2.transport.update_function._session - assert session1 != session2 - session1 = client1.transport.delete_function._session - session2 = client2.transport.delete_function._session - assert session1 != session2 - session1 = client1.transport.call_function._session - session2 = client2.transport.call_function._session - assert session1 != session2 - session1 = client1.transport.generate_upload_url._session - session2 = client2.transport.generate_upload_url._session - assert session1 != session2 - session1 = client1.transport.generate_download_url._session - session2 = client2.transport.generate_download_url._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_cloud_functions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcTransport( - 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_cloud_functions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CloudFunctionsServiceGrpcAsyncIOTransport( - 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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_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.CloudFunctionsServiceGrpcTransport, transports.CloudFunctionsServiceGrpcAsyncIOTransport]) -def test_cloud_functions_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_cloud_functions_service_grpc_lro_client(): - client = CloudFunctionsServiceClient( - 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_cloud_functions_service_grpc_lro_async_client(): - client = CloudFunctionsServiceAsyncClient( - 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_cloud_function_path(): - project = "squid" - location = "clam" - function = "whelk" - expected = "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) - actual = CloudFunctionsServiceClient.cloud_function_path(project, location, function) - assert expected == actual - - -def test_parse_cloud_function_path(): - expected = { - "project": "octopus", - "location": "oyster", - "function": "nudibranch", - } - path = CloudFunctionsServiceClient.cloud_function_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_cloud_function_path(path) - assert expected == actual - -def test_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = CloudFunctionsServiceClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "crypto_key": "clam", - } - path = CloudFunctionsServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_repository_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - expected = "projects/{project}/locations/{location}/repositories/{repository}".format(project=project, location=location, repository=repository, ) - actual = CloudFunctionsServiceClient.repository_path(project, location, repository) - assert expected == actual - - -def test_parse_repository_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "repository": "mussel", - } - path = CloudFunctionsServiceClient.repository_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_repository_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CloudFunctionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = CloudFunctionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = CloudFunctionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = CloudFunctionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CloudFunctionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = CloudFunctionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = CloudFunctionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = CloudFunctionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CloudFunctionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = CloudFunctionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CloudFunctionsServiceClient.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.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CloudFunctionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CloudFunctionsServiceClient.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 = CloudFunctionsServiceAsyncClient( - 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_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'operations/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'operations/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = CloudFunctionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = CloudFunctionsServiceClient( - 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_async(transport: str = "grpc_asyncio"): - client = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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_async(transport: str = "grpc_asyncio"): - client = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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_async(transport: str = "grpc_asyncio"): - client = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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 = CloudFunctionsServiceClient( - 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 = CloudFunctionsServiceAsyncClient( - 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_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CloudFunctionsServiceClient( - 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 = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = CloudFunctionsServiceClient( - 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", [ - (CloudFunctionsServiceClient, transports.CloudFunctionsServiceGrpcTransport), - (CloudFunctionsServiceAsyncClient, transports.CloudFunctionsServiceGrpcAsyncIOTransport), -]) -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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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, - ) diff --git a/owl-bot-staging/google-cloud-functions/v2/.coveragerc b/owl-bot-staging/google-cloud-functions/v2/.coveragerc deleted file mode 100644 index 3409ddad4fe3..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/functions/__init__.py - google/cloud/functions/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-functions/v2/.flake8 b/owl-bot-staging/google-cloud-functions/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-functions/v2/MANIFEST.in b/owl-bot-staging/google-cloud-functions/v2/MANIFEST.in deleted file mode 100644 index 3e1982064c0f..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/functions *.py -recursive-include google/cloud/functions_v2 *.py diff --git a/owl-bot-staging/google-cloud-functions/v2/README.rst b/owl-bot-staging/google-cloud-functions/v2/README.rst deleted file mode 100644 index 533650ad477c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Functions API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Functions API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-functions/v2/docs/_static/custom.css b/owl-bot-staging/google-cloud-functions/v2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-functions/v2/docs/conf.py b/owl-bot-staging/google-cloud-functions/v2/docs/conf.py deleted file mode 100644 index 92a2c45f25e2..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# -# google-cloud-functions documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-functions" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-functions-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-functions.tex", - u"google-cloud-functions Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-functions", - u"Google Cloud Functions Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-functions", - u"google-cloud-functions Documentation", - author, - "google-cloud-functions", - "GAPIC library for Google Cloud Functions API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/function_service.rst b/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/function_service.rst deleted file mode 100644 index 03a513276d6a..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/function_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -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/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/services_.rst b/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/services_.rst deleted file mode 100644 index a2004da21794..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Functions v2 API -========================================== -.. toctree:: - :maxdepth: 2 - - function_service diff --git a/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/types_.rst b/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/types_.rst deleted file mode 100644 index 57ad3591497b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/functions_v2/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Functions v2 API -======================================= - -.. automodule:: google.cloud.functions_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-functions/v2/docs/index.rst b/owl-bot-staging/google-cloud-functions/v2/docs/index.rst deleted file mode 100644 index 15756cf17279..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - functions_v2/services - functions_v2/types diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/__init__.py deleted file mode 100644 index 1088925ce073..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/__init__.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.cloud.functions import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.functions_v2.services.function_service.client import FunctionServiceClient -from google.cloud.functions_v2.services.function_service.async_client import FunctionServiceAsyncClient - -from google.cloud.functions_v2.types.functions import BuildConfig -from google.cloud.functions_v2.types.functions import CreateFunctionRequest -from google.cloud.functions_v2.types.functions import DeleteFunctionRequest -from google.cloud.functions_v2.types.functions import EventFilter -from google.cloud.functions_v2.types.functions import EventTrigger -from google.cloud.functions_v2.types.functions import Function -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateDownloadUrlResponse -from google.cloud.functions_v2.types.functions import GenerateUploadUrlRequest -from google.cloud.functions_v2.types.functions import GenerateUploadUrlResponse -from google.cloud.functions_v2.types.functions import GetFunctionRequest -from google.cloud.functions_v2.types.functions import ListFunctionsRequest -from google.cloud.functions_v2.types.functions import ListFunctionsResponse -from google.cloud.functions_v2.types.functions import ListRuntimesRequest -from google.cloud.functions_v2.types.functions import ListRuntimesResponse -from google.cloud.functions_v2.types.functions import LocationMetadata -from google.cloud.functions_v2.types.functions import OperationMetadata -from google.cloud.functions_v2.types.functions import RepoSource -from google.cloud.functions_v2.types.functions import SecretEnvVar -from google.cloud.functions_v2.types.functions import SecretVolume -from google.cloud.functions_v2.types.functions import ServiceConfig -from google.cloud.functions_v2.types.functions import Source -from google.cloud.functions_v2.types.functions import SourceProvenance -from google.cloud.functions_v2.types.functions import Stage -from google.cloud.functions_v2.types.functions import StateMessage -from google.cloud.functions_v2.types.functions import StorageSource -from google.cloud.functions_v2.types.functions import UpdateFunctionRequest -from google.cloud.functions_v2.types.functions import Environment - -__all__ = ('FunctionServiceClient', - 'FunctionServiceAsyncClient', - 'BuildConfig', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventFilter', - 'EventTrigger', - 'Function', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'ListRuntimesRequest', - 'ListRuntimesResponse', - 'LocationMetadata', - 'OperationMetadata', - 'RepoSource', - 'SecretEnvVar', - 'SecretVolume', - 'ServiceConfig', - 'Source', - 'SourceProvenance', - 'Stage', - 'StateMessage', - 'StorageSource', - 'UpdateFunctionRequest', - 'Environment', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/gapic_version.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/py.typed b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/py.typed deleted file mode 100644 index 982ebb18c324..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/__init__.py deleted file mode 100644 index 6ee13bee2374..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/__init__.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.cloud.functions_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.function_service import FunctionServiceClient -from .services.function_service import FunctionServiceAsyncClient - -from .types.functions import BuildConfig -from .types.functions import CreateFunctionRequest -from .types.functions import DeleteFunctionRequest -from .types.functions import EventFilter -from .types.functions import EventTrigger -from .types.functions import Function -from .types.functions import GenerateDownloadUrlRequest -from .types.functions import GenerateDownloadUrlResponse -from .types.functions import GenerateUploadUrlRequest -from .types.functions import GenerateUploadUrlResponse -from .types.functions import GetFunctionRequest -from .types.functions import ListFunctionsRequest -from .types.functions import ListFunctionsResponse -from .types.functions import ListRuntimesRequest -from .types.functions import ListRuntimesResponse -from .types.functions import LocationMetadata -from .types.functions import OperationMetadata -from .types.functions import RepoSource -from .types.functions import SecretEnvVar -from .types.functions import SecretVolume -from .types.functions import ServiceConfig -from .types.functions import Source -from .types.functions import SourceProvenance -from .types.functions import Stage -from .types.functions import StateMessage -from .types.functions import StorageSource -from .types.functions import UpdateFunctionRequest -from .types.functions import Environment - -__all__ = ( - 'FunctionServiceAsyncClient', -'BuildConfig', -'CreateFunctionRequest', -'DeleteFunctionRequest', -'Environment', -'EventFilter', -'EventTrigger', -'Function', -'FunctionServiceClient', -'GenerateDownloadUrlRequest', -'GenerateDownloadUrlResponse', -'GenerateUploadUrlRequest', -'GenerateUploadUrlResponse', -'GetFunctionRequest', -'ListFunctionsRequest', -'ListFunctionsResponse', -'ListRuntimesRequest', -'ListRuntimesResponse', -'LocationMetadata', -'OperationMetadata', -'RepoSource', -'SecretEnvVar', -'SecretVolume', -'ServiceConfig', -'Source', -'SourceProvenance', -'Stage', -'StateMessage', -'StorageSource', -'UpdateFunctionRequest', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_metadata.json b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_metadata.json deleted file mode 100644 index 2cb7eab20275..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_metadata.json +++ /dev/null @@ -1,148 +0,0 @@ - { - "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" - ] - } - } - }, - "rest": { - "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" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_version.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/py.typed b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/py.typed deleted file mode 100644 index 982ebb18c324..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-functions package uses inline types. diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/__init__.py deleted file mode 100644 index d4f4dc110ce5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 .client import FunctionServiceClient -from .async_client import FunctionServiceAsyncClient - -__all__ = ( - 'FunctionServiceClient', - 'FunctionServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/async_client.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/async_client.py deleted file mode 100644 index 64aba13c6511..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/async_client.py +++ /dev/null @@ -1,1651 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.functions_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions -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.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport -from .client import FunctionServiceClient - - -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 - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = FunctionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FunctionServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = FunctionServiceClient._DEFAULT_UNIVERSE - - 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) - crypto_key_path = staticmethod(FunctionServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(FunctionServiceClient.parse_crypto_key_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 variable 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 - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = functools.partial(type(FunctionServiceClient).get_transport_class, type(FunctionServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FunctionServiceTransport, Callable[..., FunctionServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the function service async 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 (Optional[Union[str,FunctionServiceTransport,Callable[..., FunctionServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the FunctionServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = FunctionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_function(self, - request: Optional[Union[functions.GetFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.Function: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.ListFunctionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsAsyncPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_function(self, - request: Optional[Union[functions.CreateFunctionRequest, dict]] = None, - *, - parent: Optional[str] = None, - function: Optional[functions.Function] = None, - function_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.UpdateFunctionRequest, dict]] = None, - *, - function: Optional[functions.Function] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates existing function. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.DeleteFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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); - - } - - """ - # 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.GenerateUploadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[Union[google.cloud.functions_v2.types.GenerateUploadUrlRequest, dict]]): - The request object. Request of ``GenerateSourceUploadUrl`` method. - retry (google.api_core.retry_async.AsyncRetry): 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.GenerateDownloadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[Union[google.cloud.functions_v2.types.GenerateDownloadUrlRequest, dict]]): - The request object. Request of ``GenerateDownloadUrl`` method. - retry (google.api_core.retry_async.AsyncRetry): 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[Union[functions.ListRuntimesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.ListRuntimesResponse: - r"""Returns a list of runtimes that are supported for the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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 (Optional[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_async.AsyncRetry): 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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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** - - :: - - { - "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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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** - - :: - - { - "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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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_async.AsyncRetry): 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_async.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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "FunctionServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FunctionServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/client.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/client.py deleted file mode 100644 index c282da8a53a9..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/client.py +++ /dev/null @@ -1,2077 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.functions_v2 import gapic_version as package_version - -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.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.types import functions -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.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FunctionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FunctionServiceGrpcTransport -from .transports.grpc_asyncio import FunctionServiceGrpcAsyncIOTransport -from .transports.rest import FunctionServiceRestTransport - - -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 - _transport_registry["rest"] = FunctionServiceRestTransport - - def get_transport_class(cls, - label: Optional[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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudfunctions.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudfunctions.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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 crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?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): - """Deprecated. 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 variable 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. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = FunctionServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = FunctionServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = FunctionServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FunctionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - FunctionServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FunctionServiceTransport, Callable[..., FunctionServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = 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 (Optional[Union[str,FunctionServiceTransport,Callable[..., FunctionServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the FunctionServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = FunctionServiceClient._read_environment_variables() - self._client_cert_source = FunctionServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = FunctionServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, FunctionServiceTransport) - if transport_provided: - # transport is a FunctionServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(FunctionServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - FunctionServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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_init: Union[Type[FunctionServiceTransport], Callable[..., FunctionServiceTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., FunctionServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def get_function(self, - request: Optional[Union[functions.GetFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.Function: - r"""Returns a function with the given name from the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_functions(self, - request: Optional[Union[functions.ListFunctionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFunctionsPager: - r"""Returns a list of functions that belong to the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_function(self, - request: Optional[Union[functions.CreateFunctionRequest, dict]] = None, - *, - parent: Optional[str] = None, - function: Optional[functions.Function] = None, - function_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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: Optional[Union[functions.UpdateFunctionRequest, dict]] = None, - *, - function: Optional[functions.Function] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates existing function. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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: Optional[Union[functions.DeleteFunctionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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); - - } - - """ - # 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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: Optional[Union[functions.GenerateUploadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_download_url(self, - request: Optional[Union[functions.GenerateDownloadUrlRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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 - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_runtimes(self, - request: Optional[Union[functions.ListRuntimesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> functions.ListRuntimesResponse: - r"""Returns a list of runtimes that are supported for the - requested project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import 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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "FunctionServiceClient": - 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: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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** - - :: - - { - "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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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** - - :: - - { - "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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FunctionServiceClient", -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/pagers.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/pagers.py deleted file mode 100644 index 966b53f38ccf..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -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, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - 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. - """ - self._method = method - self._request = functions.ListFunctionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - 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, retry=self._retry, timeout=self._timeout, 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, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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. - retry (google.api_core.retry.AsyncRetry): 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. - """ - self._method = method - self._request = functions.ListFunctionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - 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, retry=self._retry, timeout=self._timeout, 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/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py deleted file mode 100644 index 28ff8509cc84..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 -from .rest import FunctionServiceRestTransport -from .rest import FunctionServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FunctionServiceTransport]] -_transport_registry['grpc'] = FunctionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = FunctionServiceGrpcAsyncIOTransport -_transport_registry['rest'] = FunctionServiceRestTransport - -__all__ = ( - 'FunctionServiceTransport', - 'FunctionServiceGrpcTransport', - 'FunctionServiceGrpcAsyncIOTransport', - 'FunctionServiceRestTransport', - 'FunctionServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/base.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/base.py deleted file mode 100644 index 38c1313c24c7..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/base.py +++ /dev/null @@ -1,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 - -from google.cloud.functions_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -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 import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.functions_v2.types import functions -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 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -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: Optional[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 (default: 'cloudfunctions.googleapis.com'). - 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 not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - 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 - - @property - def host(self): - return self._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/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py deleted file mode 100644 index 9035e410df3e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc.py +++ /dev/null @@ -1,651 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_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 - -import grpc # type: ignore - -from google.cloud.functions_v2.types import functions -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 .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO - - -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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[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/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py deleted file mode 100644 index cc1704aec81e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,696 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.functions_v2.types import functions -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 .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO -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: Optional[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`. - 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: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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 _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_function: gapic_v1.method_async.wrap_method( - self.get_function, - default_timeout=None, - client_info=client_info, - ), - self.list_functions: gapic_v1.method_async.wrap_method( - self.list_functions, - default_timeout=None, - client_info=client_info, - ), - self.create_function: gapic_v1.method_async.wrap_method( - self.create_function, - default_timeout=None, - client_info=client_info, - ), - self.update_function: gapic_v1.method_async.wrap_method( - self.update_function, - default_timeout=None, - client_info=client_info, - ), - self.delete_function: gapic_v1.method_async.wrap_method( - self.delete_function, - default_timeout=None, - client_info=client_info, - ), - self.generate_upload_url: gapic_v1.method_async.wrap_method( - self.generate_upload_url, - default_timeout=None, - client_info=client_info, - ), - self.generate_download_url: gapic_v1.method_async.wrap_method( - self.generate_download_url, - default_timeout=None, - client_info=client_info, - ), - self.list_runtimes: gapic_v1.method_async.wrap_method( - self.list_runtimes, - default_timeout=None, - client_info=client_info, - ), - } - - 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/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/rest.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/rest.py deleted file mode 100644 index 9470ca1cc9a5..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/services/function_service/transports/rest.py +++ /dev/null @@ -1,1654 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.functions_v2.types import functions -from google.longrunning import operations_pb2 # type: ignore - -from .base import FunctionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class FunctionServiceRestInterceptor: - """Interceptor for FunctionService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the FunctionServiceRestTransport. - - .. code-block:: python - class MyCustomFunctionServiceInterceptor(FunctionServiceRestInterceptor): - def pre_create_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_download_url(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_download_url(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_upload_url(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_upload_url(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_function(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_functions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_functions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_runtimes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_runtimes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_function(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_function(self, response): - logging.log(f"Received response: {response}") - return response - - transport = FunctionServiceRestTransport(interceptor=MyCustomFunctionServiceInterceptor()) - client = FunctionServiceClient(transport=transport) - - - """ - def pre_create_function(self, request: functions.CreateFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.CreateFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_create_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_function - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_delete_function(self, request: functions.DeleteFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.DeleteFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_delete_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_function - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_generate_download_url(self, request: functions.GenerateDownloadUrlRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GenerateDownloadUrlRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_download_url - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_generate_download_url(self, response: functions.GenerateDownloadUrlResponse) -> functions.GenerateDownloadUrlResponse: - """Post-rpc interceptor for generate_download_url - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_generate_upload_url(self, request: functions.GenerateUploadUrlRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GenerateUploadUrlRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_upload_url - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_generate_upload_url(self, response: functions.GenerateUploadUrlResponse) -> functions.GenerateUploadUrlResponse: - """Post-rpc interceptor for generate_upload_url - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_get_function(self, request: functions.GetFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.GetFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_get_function(self, response: functions.Function) -> functions.Function: - """Post-rpc interceptor for get_function - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_list_functions(self, request: functions.ListFunctionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.ListFunctionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_functions - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_list_functions(self, response: functions.ListFunctionsResponse) -> functions.ListFunctionsResponse: - """Post-rpc interceptor for list_functions - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_list_runtimes(self, request: functions.ListRuntimesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.ListRuntimesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_runtimes - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_list_runtimes(self, response: functions.ListRuntimesResponse) -> functions.ListRuntimesResponse: - """Post-rpc interceptor for list_runtimes - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_update_function(self, request: functions.UpdateFunctionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[functions.UpdateFunctionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_function - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_update_function(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_function - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the FunctionService server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the FunctionService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class FunctionServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: FunctionServiceRestInterceptor - - -class FunctionServiceRestTransport(FunctionServiceTransport): - """REST 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'cloudfunctions.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[FunctionServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudfunctions.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or FunctionServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFunction(FunctionServiceRestStub): - def __hash__(self): - return hash("CreateFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.CreateFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create function method over HTTP. - - Args: - request (~.functions.CreateFunctionRequest): - The request object. Request for the ``CreateFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/functions', - 'body': 'function', - }, - ] - request, metadata = self._interceptor.pre_create_function(request, metadata) - pb_request = functions.CreateFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_function(resp) - return resp - - class _DeleteFunction(FunctionServiceRestStub): - def __hash__(self): - return hash("DeleteFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.DeleteFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete function method over HTTP. - - Args: - request (~.functions.DeleteFunctionRequest): - The request object. Request for the ``DeleteFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/functions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_function(request, metadata) - pb_request = functions.DeleteFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_function(resp) - return resp - - class _GenerateDownloadUrl(FunctionServiceRestStub): - def __hash__(self): - return hash("GenerateDownloadUrl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.GenerateDownloadUrlRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.GenerateDownloadUrlResponse: - r"""Call the generate download url method over HTTP. - - Args: - request (~.functions.GenerateDownloadUrlRequest): - 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: - ~.functions.GenerateDownloadUrlResponse: - Response of ``GenerateDownloadUrl`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/functions/*}:generateDownloadUrl', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_download_url(request, metadata) - pb_request = functions.GenerateDownloadUrlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.GenerateDownloadUrlResponse() - pb_resp = functions.GenerateDownloadUrlResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_download_url(resp) - return resp - - class _GenerateUploadUrl(FunctionServiceRestStub): - def __hash__(self): - return hash("GenerateUploadUrl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.GenerateUploadUrlRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.GenerateUploadUrlResponse: - r"""Call the generate upload url method over HTTP. - - Args: - request (~.functions.GenerateUploadUrlRequest): - 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: - ~.functions.GenerateUploadUrlResponse: - Response of ``GenerateSourceUploadUrl`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/functions:generateUploadUrl', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_upload_url(request, metadata) - pb_request = functions.GenerateUploadUrlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.GenerateUploadUrlResponse() - pb_resp = functions.GenerateUploadUrlResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_upload_url(resp) - return resp - - class _GetFunction(FunctionServiceRestStub): - def __hash__(self): - return hash("GetFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.GetFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.Function: - r"""Call the get function method over HTTP. - - Args: - request (~.functions.GetFunctionRequest): - The request object. Request for the ``GetFunction`` 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: - ~.functions.Function: - Describes a Cloud Function that - contains user computation executed in - response to an event. It encapsulates - function and trigger configurations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/functions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_function(request, metadata) - pb_request = functions.GetFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.Function() - pb_resp = functions.Function.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_function(resp) - return resp - - class _ListFunctions(FunctionServiceRestStub): - def __hash__(self): - return hash("ListFunctions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.ListFunctionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.ListFunctionsResponse: - r"""Call the list functions method over HTTP. - - Args: - request (~.functions.ListFunctionsRequest): - The request object. Request for the ``ListFunctions`` 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: - ~.functions.ListFunctionsResponse: - Response for the ``ListFunctions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/functions', - }, - ] - request, metadata = self._interceptor.pre_list_functions(request, metadata) - pb_request = functions.ListFunctionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.ListFunctionsResponse() - pb_resp = functions.ListFunctionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_functions(resp) - return resp - - class _ListRuntimes(FunctionServiceRestStub): - def __hash__(self): - return hash("ListRuntimes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.ListRuntimesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> functions.ListRuntimesResponse: - r"""Call the list runtimes method over HTTP. - - Args: - request (~.functions.ListRuntimesRequest): - The request object. Request for the ``ListRuntimes`` 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: - ~.functions.ListRuntimesResponse: - Response for the ``ListRuntimes`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/runtimes', - }, - ] - request, metadata = self._interceptor.pre_list_runtimes(request, metadata) - pb_request = functions.ListRuntimesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = functions.ListRuntimesResponse() - pb_resp = functions.ListRuntimesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_runtimes(resp) - return resp - - class _UpdateFunction(FunctionServiceRestStub): - def __hash__(self): - return hash("UpdateFunction") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: functions.UpdateFunctionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update function method over HTTP. - - Args: - request (~.functions.UpdateFunctionRequest): - The request object. Request for the ``UpdateFunction`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{function.name=projects/*/locations/*/functions/*}', - 'body': 'function', - }, - ] - request, metadata = self._interceptor.pre_update_function(request, metadata) - pb_request = functions.UpdateFunctionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_function(resp) - return resp - - @property - def create_function(self) -> Callable[ - [functions.CreateFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_function(self) -> Callable[ - [functions.DeleteFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_download_url(self) -> Callable[ - [functions.GenerateDownloadUrlRequest], - functions.GenerateDownloadUrlResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateDownloadUrl(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_upload_url(self) -> Callable[ - [functions.GenerateUploadUrlRequest], - functions.GenerateUploadUrlResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateUploadUrl(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_function(self) -> Callable[ - [functions.GetFunctionRequest], - functions.Function]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_functions(self) -> Callable[ - [functions.ListFunctionsRequest], - functions.ListFunctionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFunctions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_runtimes(self) -> Callable[ - [functions.ListRuntimesRequest], - functions.ListRuntimesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListRuntimes(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_function(self) -> Callable[ - [functions.UpdateFunctionRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateFunction(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(FunctionServiceRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(FunctionServiceRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{resource=projects/*/locations/*/functions/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(FunctionServiceRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=projects/*/locations/*/functions/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(FunctionServiceRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=projects/*/locations/*/functions/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(FunctionServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(FunctionServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'FunctionServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/__init__.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/__init__.py deleted file mode 100644 index 7a6783e26c1e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/__init__.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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, - EventFilter, - EventTrigger, - Function, - GenerateDownloadUrlRequest, - GenerateDownloadUrlResponse, - GenerateUploadUrlRequest, - GenerateUploadUrlResponse, - GetFunctionRequest, - ListFunctionsRequest, - ListFunctionsResponse, - ListRuntimesRequest, - ListRuntimesResponse, - LocationMetadata, - OperationMetadata, - RepoSource, - SecretEnvVar, - SecretVolume, - ServiceConfig, - Source, - SourceProvenance, - Stage, - StateMessage, - StorageSource, - UpdateFunctionRequest, - Environment, -) - -__all__ = ( - 'BuildConfig', - 'CreateFunctionRequest', - 'DeleteFunctionRequest', - 'EventFilter', - 'EventTrigger', - 'Function', - 'GenerateDownloadUrlRequest', - 'GenerateDownloadUrlResponse', - 'GenerateUploadUrlRequest', - 'GenerateUploadUrlResponse', - 'GetFunctionRequest', - 'ListFunctionsRequest', - 'ListFunctionsResponse', - 'ListRuntimesRequest', - 'ListRuntimesResponse', - 'LocationMetadata', - 'OperationMetadata', - 'RepoSource', - 'SecretEnvVar', - 'SecretVolume', - 'ServiceConfig', - 'Source', - 'SourceProvenance', - 'Stage', - 'StateMessage', - 'StorageSource', - 'UpdateFunctionRequest', - 'Environment', -) diff --git a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/functions.py b/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/functions.py deleted file mode 100644 index e8bd5dd62075..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/google/cloud/functions_v2/types/functions.py +++ /dev/null @@ -1,1635 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -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 - - -__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', - 'LocationMetadata', - 'Stage', - }, -) - - -class Environment(proto.Enum): - r"""The environment the function is hosted on. - - Values: - ENVIRONMENT_UNSPECIFIED (0): - Unspecified - GEN_1 (1): - Gen 1 - GEN_2 (2): - Gen 2 - """ - 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/*`` - 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 (MutableMapping[str, str]): - Labels associated with this Cloud Function. - state_messages (MutableSequence[google.cloud.functions_v2.types.StateMessage]): - Output only. State Messages for this Cloud - Function. - environment (google.cloud.functions_v2.types.Environment): - Describe whether the function is 1st Gen or - 2nd Gen. - url (str): - Output only. The deployed url for the - function. - kms_key_name (str): - [Preview] Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt function resources. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - """ - class State(proto.Enum): - r"""Describes the current state of the function. - - Values: - STATE_UNSPECIFIED (0): - Not specified. Invalid state. - ACTIVE (1): - Function has been successfully deployed and - is serving. - FAILED (2): - Function deployment failed and the function - is not serving. - DEPLOYING (3): - Function is being created or updated. - DELETING (4): - Function is being deleted. - UNKNOWN (5): - Function deployment failed and the function - serving state is undefined. The function should - be updated or deleted to move it out of this - state. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - FAILED = 2 - DEPLOYING = 3 - DELETING = 4 - UNKNOWN = 5 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - build_config: 'BuildConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='BuildConfig', - ) - service_config: 'ServiceConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='ServiceConfig', - ) - event_trigger: 'EventTrigger' = proto.Field( - proto.MESSAGE, - number=5, - message='EventTrigger', - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - state_messages: MutableSequence['StateMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='StateMessage', - ) - environment: 'Environment' = proto.Field( - proto.ENUM, - number=10, - enum='Environment', - ) - url: str = proto.Field( - proto.STRING, - number=14, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=25, - ) - - -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. - - Values: - SEVERITY_UNSPECIFIED (0): - Not specified. Invalid severity. - ERROR (1): - ERROR-level severity. - WARNING (2): - WARNING-level severity. - INFO (3): - INFO-level severity. - """ - SEVERITY_UNSPECIFIED = 0 - ERROR = 1 - WARNING = 2 - INFO = 3 - - severity: Severity = proto.Field( - proto.ENUM, - number=1, - enum=Severity, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - message: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - object_: str = proto.Field( - proto.STRING, - number=2, - ) - generation: int = 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: str = proto.Field( - proto.STRING, - number=3, - oneof='revision', - ) - tag_name: str = proto.Field( - proto.STRING, - number=4, - oneof='revision', - ) - commit_sha: str = proto.Field( - proto.STRING, - number=5, - oneof='revision', - ) - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - repo_name: str = proto.Field( - proto.STRING, - number=2, - ) - dir_: str = proto.Field( - proto.STRING, - number=6, - ) - invert_regex: bool = 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: 'StorageSource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='source', - message='StorageSource', - ) - repo_source: 'RepoSource' = 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: 'StorageSource' = proto.Field( - proto.MESSAGE, - number=1, - message='StorageSource', - ) - resolved_repo_source: 'RepoSource' = 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 (MutableMapping[str, str]): - User-provided build-time environment - variables for the function - docker_registry (google.cloud.functions_v2.types.BuildConfig.DockerRegistry): - Docker Registry to use for this deployment. This - configuration is only applicable to 1st Gen functions, 2nd - Gen functions can only use Artifact Registry. - - If ``docker_repository`` field is specified, this field will - be automatically set as ``ARTIFACT_REGISTRY``. If - unspecified, it currently defaults to - ``CONTAINER_REGISTRY``. This field may be overridden by the - backend for eligible deployments. - docker_repository (str): - 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'. - """ - class DockerRegistry(proto.Enum): - r"""Docker Registry to use for storing function Docker images. - - Values: - DOCKER_REGISTRY_UNSPECIFIED (0): - Unspecified. - CONTAINER_REGISTRY (1): - Docker images will be stored in multi-regional Container - Registry repositories named ``gcf``. - ARTIFACT_REGISTRY (2): - Docker images will be stored in regional Artifact Registry - repositories. By default, GCF will create and use - repositories named ``gcf-artifacts`` in every region in - which a function is deployed. But the repository to use can - also be specified by the user using the - ``docker_repository`` field. - """ - DOCKER_REGISTRY_UNSPECIFIED = 0 - CONTAINER_REGISTRY = 1 - ARTIFACT_REGISTRY = 2 - - build: str = proto.Field( - proto.STRING, - number=1, - ) - runtime: str = proto.Field( - proto.STRING, - number=2, - ) - entry_point: str = proto.Field( - proto.STRING, - number=3, - ) - source: 'Source' = proto.Field( - proto.MESSAGE, - number=4, - message='Source', - ) - source_provenance: 'SourceProvenance' = proto.Field( - proto.MESSAGE, - number=8, - message='SourceProvenance', - ) - worker_pool: str = proto.Field( - proto.STRING, - number=5, - ) - environment_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - docker_registry: DockerRegistry = proto.Field( - proto.ENUM, - number=10, - enum=DockerRegistry, - ) - docker_repository: str = 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. - available_cpu (str): - [Preview] The number of CPUs used in a single container - instance. Default value is calculated from available memory. - Supports the same values as Cloud Run, see - https://cloud.google.com/run/docs/reference/rest/v1/Container#resourcerequirements - Example: "1" indicates 1 vCPU - environment_variables (MutableMapping[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 (MutableSequence[google.cloud.functions_v2.types.SecretEnvVar]): - Secret environment variables configuration. - secret_volumes (MutableSequence[google.cloud.functions_v2.types.SecretVolume]): - Secret volumes configuration. - revision (str): - Output only. The name of service revision. - max_instance_request_concurrency (int): - [Preview] Sets the maximum number of concurrent requests - that each instance can receive. Defaults to 1. - security_level (google.cloud.functions_v2.types.ServiceConfig.SecurityLevel): - Security level configure whether the function - only accepts https. This configuration is only - applicable to 1st Gen functions with Http - trigger. By default https is optional for 1st - Gen functions; 2nd Gen functions are https ONLY. - """ - 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. - - Values: - VPC_CONNECTOR_EGRESS_SETTINGS_UNSPECIFIED (0): - Unspecified. - PRIVATE_RANGES_ONLY (1): - Use the VPC Access Connector only for private - IP space from RFC1918. - ALL_TRAFFIC (2): - Force the use of VPC Access Connector for all - egress traffic from the function. - """ - 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. - - Values: - INGRESS_SETTINGS_UNSPECIFIED (0): - Unspecified. - ALLOW_ALL (1): - Allow HTTP traffic from public and private - sources. - ALLOW_INTERNAL_ONLY (2): - Allow HTTP traffic from only private VPC - sources. - ALLOW_INTERNAL_AND_GCLB (3): - Allow HTTP traffic from private VPC sources - and through GCLB. - """ - INGRESS_SETTINGS_UNSPECIFIED = 0 - ALLOW_ALL = 1 - ALLOW_INTERNAL_ONLY = 2 - ALLOW_INTERNAL_AND_GCLB = 3 - - class SecurityLevel(proto.Enum): - r"""Available security level settings. - - This enforces security protocol on function URL. - - Security level is only configurable for 1st Gen functions, If - unspecified, SECURE_OPTIONAL will be used. 2nd Gen functions are - SECURE_ALWAYS ONLY. - - Values: - SECURITY_LEVEL_UNSPECIFIED (0): - Unspecified. - SECURE_ALWAYS (1): - Requests for a URL that match this handler - that do not use HTTPS are automatically - redirected to the HTTPS URL with the same path. - Query parameters are reserved for the redirect. - SECURE_OPTIONAL (2): - Both HTTP and HTTPS requests with URLs that - match the handler succeed without redirects. The - application can examine the request to determine - which protocol was used and respond accordingly. - """ - SECURITY_LEVEL_UNSPECIFIED = 0 - SECURE_ALWAYS = 1 - SECURE_OPTIONAL = 2 - - service: str = proto.Field( - proto.STRING, - number=1, - ) - timeout_seconds: int = proto.Field( - proto.INT32, - number=2, - ) - available_memory: str = proto.Field( - proto.STRING, - number=13, - ) - available_cpu: str = proto.Field( - proto.STRING, - number=22, - ) - environment_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - max_instance_count: int = proto.Field( - proto.INT32, - number=5, - ) - min_instance_count: int = proto.Field( - proto.INT32, - number=12, - ) - vpc_connector: str = proto.Field( - proto.STRING, - number=6, - ) - vpc_connector_egress_settings: VpcConnectorEgressSettings = proto.Field( - proto.ENUM, - number=7, - enum=VpcConnectorEgressSettings, - ) - ingress_settings: IngressSettings = proto.Field( - proto.ENUM, - number=8, - enum=IngressSettings, - ) - uri: str = proto.Field( - proto.STRING, - number=9, - ) - service_account_email: str = proto.Field( - proto.STRING, - number=10, - ) - all_traffic_on_latest_revision: bool = proto.Field( - proto.BOOL, - number=16, - ) - secret_environment_variables: MutableSequence['SecretEnvVar'] = proto.RepeatedField( - proto.MESSAGE, - number=17, - message='SecretEnvVar', - ) - secret_volumes: MutableSequence['SecretVolume'] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message='SecretVolume', - ) - revision: str = proto.Field( - proto.STRING, - number=18, - ) - max_instance_request_concurrency: int = proto.Field( - proto.INT32, - number=20, - ) - security_level: SecurityLevel = proto.Field( - proto.ENUM, - number=21, - enum=SecurityLevel, - ) - - -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: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - secret: str = proto.Field( - proto.STRING, - number=3, - ) - version: str = 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 (MutableSequence[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: str = proto.Field( - proto.STRING, - number=1, - ) - path: str = proto.Field( - proto.STRING, - number=2, - ) - - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - project_id: str = proto.Field( - proto.STRING, - number=2, - ) - secret: str = proto.Field( - proto.STRING, - number=3, - ) - versions: MutableSequence[SecretVersion] = 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 (MutableSequence[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. - - Values: - RETRY_POLICY_UNSPECIFIED (0): - Not specified. - RETRY_POLICY_DO_NOT_RETRY (1): - Do not retry. - RETRY_POLICY_RETRY (2): - Retry on any failure, retry up to 7 days with - an exponential backoff (capped at 10 seconds). - """ - RETRY_POLICY_UNSPECIFIED = 0 - RETRY_POLICY_DO_NOT_RETRY = 1 - RETRY_POLICY_RETRY = 2 - - trigger: str = proto.Field( - proto.STRING, - number=1, - ) - trigger_region: str = proto.Field( - proto.STRING, - number=2, - ) - event_type: str = proto.Field( - proto.STRING, - number=3, - ) - event_filters: MutableSequence['EventFilter'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='EventFilter', - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=5, - ) - service_account_email: str = proto.Field( - proto.STRING, - number=6, - ) - retry_policy: RetryPolicy = proto.Field( - proto.ENUM, - number=7, - enum=RetryPolicy, - ) - channel: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - operator: str = 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: str = 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. The largest - allowed page_size is 1,000, if the page_size is omitted or - specified as greater than 1,000 then it will be replaced as - 1,000. The size of the list response can be less than - specified when used with filters. - 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: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListFunctionsResponse(proto.Message): - r"""Response for the ``ListFunctions`` method. - - Attributes: - functions (MutableSequence[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 (MutableSequence[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: MutableSequence['Function'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Function', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = 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: str = proto.Field( - proto.STRING, - number=1, - ) - function: 'Function' = proto.Field( - proto.MESSAGE, - number=2, - message='Function', - ) - function_id: str = 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: 'Function' = proto.Field( - proto.MESSAGE, - number=1, - message='Function', - ) - update_mask: field_mask_pb2.FieldMask = 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: str = 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/*``. - kms_key_name (str): - [Preview] Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt function source code objects - in intermediate Cloud Storage buckets. When you generate an - upload url and upload your source code, it gets copied to an - intermediate Cloud Storage bucket. The source code is then - copied to a versioned directory in the sources bucket in the - consumer project during the function deployment. - - It must match the pattern - ``projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}``. - - The Google Cloud Functions service account - (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - must be granted the role 'Cloud KMS CryptoKey - Encrypter/Decrypter - (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the - Key/KeyRing/Project/Organization (least access preferred). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -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: str = proto.Field( - proto.STRING, - number=1, - ) - storage_source: 'StorageSource' = 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: str = 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: str = 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: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListRuntimesResponse(proto.Message): - r"""Response for the ``ListRuntimes`` method. - - Attributes: - runtimes (MutableSequence[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. - - Values: - RUNTIME_STAGE_UNSPECIFIED (0): - Not specified. - DEVELOPMENT (1): - The runtime is in development. - ALPHA (2): - The runtime is in the Alpha stage. - BETA (3): - The runtime is in the Beta stage. - GA (4): - The runtime is generally available. - DEPRECATED (5): - The runtime is deprecated. - DECOMMISSIONED (6): - The runtime is no longer supported. - """ - 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 (MutableSequence[str]): - Warning messages, e.g., a deprecation - warning. - environment (google.cloud.functions_v2.types.Environment): - The environment for the runtime. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=5, - ) - stage: 'ListRuntimesResponse.RuntimeStage' = proto.Field( - proto.ENUM, - number=2, - enum='ListRuntimesResponse.RuntimeStage', - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - environment: 'Environment' = proto.Field( - proto.ENUM, - number=4, - enum='Environment', - ) - - runtimes: MutableSequence[Runtime] = 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 (MutableSequence[google.cloud.functions_v2.types.Stage]): - Mechanism for reporting in-progress stages - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_detail: str = proto.Field( - proto.STRING, - number=5, - ) - cancel_requested: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - request_resource: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=8, - message=any_pb2.Any, - ) - stages: MutableSequence['Stage'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='Stage', - ) - - -class LocationMetadata(proto.Message): - r"""Extra GCF specific location information. - - Attributes: - environments (MutableSequence[google.cloud.functions_v2.types.Environment]): - The Cloud Function environments this location - supports. - """ - - environments: MutableSequence['Environment'] = proto.RepeatedField( - proto.ENUM, - number=1, - enum='Environment', - ) - - -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 (MutableSequence[google.cloud.functions_v2.types.StateMessage]): - State messages from the current Stage. - """ - class Name(proto.Enum): - r"""Possible names for a Stage - - Values: - NAME_UNSPECIFIED (0): - Not specified. Invalid name. - ARTIFACT_REGISTRY (1): - Artifact Regsitry Stage - BUILD (2): - Build Stage - SERVICE (3): - Service Stage - TRIGGER (4): - Trigger Stage - SERVICE_ROLLBACK (5): - Service Rollback Stage - TRIGGER_ROLLBACK (6): - Trigger Rollback 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 - - Values: - STATE_UNSPECIFIED (0): - Not specified. Invalid state. - NOT_STARTED (1): - Stage has not started. - IN_PROGRESS (2): - Stage is in progress. - COMPLETE (3): - Stage has completed. - """ - STATE_UNSPECIFIED = 0 - NOT_STARTED = 1 - IN_PROGRESS = 2 - COMPLETE = 3 - - name: Name = proto.Field( - proto.ENUM, - number=1, - enum=Name, - ) - message: str = proto.Field( - proto.STRING, - number=2, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - resource: str = proto.Field( - proto.STRING, - number=4, - ) - resource_uri: str = proto.Field( - proto.STRING, - number=5, - ) - state_messages: MutableSequence['StateMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='StateMessage', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-functions/v2/mypy.ini b/owl-bot-staging/google-cloud-functions/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-functions/v2/noxfile.py b/owl-bot-staging/google-cloud-functions/v2/noxfile.py deleted file mode 100644 index 458056da97ea..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-functions' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/functions_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - 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", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py deleted file mode 100644 index 262b9ca8a0dc..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py deleted file mode 100644 index 1b5daeed678c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_create_function_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py deleted file mode 100644 index 93f9cfc740f7..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py deleted file mode 100644 index e6989b2afd70..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_delete_function_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py deleted file mode 100644 index d477bb1af246..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py deleted file mode 100644 index bd464f300ffd..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_download_url_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py deleted file mode 100644 index fe90bb8ecf2e..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py deleted file mode 100644 index 0c4091419800..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_generate_upload_url_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py deleted file mode 100644 index 040b9aede247..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py deleted file mode 100644 index c4659caea8d9..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_get_function_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py deleted file mode 100644 index 080b84da855c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py deleted file mode 100644 index 73d694b8f606..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_functions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py deleted file mode 100644 index a7772730a4c7..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py deleted file mode 100644 index 9f2068a53721..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_list_runtimes_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py deleted file mode 100644 index e9a7854a43a1..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py deleted file mode 100644 index f86534bc6448..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/cloudfunctions_v2_generated_function_service_update_function_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import 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/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json b/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json deleted file mode 100644 index 0dbb0a2efac1..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json +++ /dev/null @@ -1,1311 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.functions.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-functions", - "version": "0.1.0" - }, - "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": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudfunctions_v2_generated_function_service_update_function_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-functions/v2/scripts/fixup_functions_v2_keywords.py b/owl-bot-staging/google-cloud-functions/v2/scripts/fixup_functions_v2_keywords.py deleted file mode 100644 index 3aaebdbcfd30..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/scripts/fixup_functions_v2_keywords.py +++ /dev/null @@ -1,183 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 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', 'kms_key_name', ), - '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/owl-bot-staging/google-cloud-functions/v2/setup.py b/owl-bot-staging/google-cloud-functions/v2/setup.py deleted file mode 100644 index 03ce0d0f560d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/setup.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-functions' - - -description = "Google Cloud Functions API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/functions/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.7.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 "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-functions/v2/tests/__init__.py b/owl-bot-staging/google-cloud-functions/v2/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-functions/v2/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/__init__.py b/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 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/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/test_function_service.py b/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/test_function_service.py deleted file mode 100644 index 2b6fe83c373c..000000000000 --- a/owl-bot-staging/google-cloud-functions/v2/tests/unit/gapic/functions_v2/test_function_service.py +++ /dev/null @@ -1,8010 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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 # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.functions_v2.services.function_service import FunctionServiceAsyncClient -from google.cloud.functions_v2.services.function_service import FunctionServiceClient -from google.cloud.functions_v2.services.function_service import pagers -from google.cloud.functions_v2.services.function_service import transports -from google.cloud.functions_v2.types import functions -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 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 - -def test__read_environment_variables(): - assert FunctionServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert FunctionServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert FunctionServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - FunctionServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert FunctionServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert FunctionServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert FunctionServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - FunctionServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert FunctionServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert FunctionServiceClient._get_client_cert_source(None, False) is None - assert FunctionServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert FunctionServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert FunctionServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert FunctionServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(FunctionServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = FunctionServiceClient._DEFAULT_UNIVERSE - default_endpoint = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert FunctionServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert FunctionServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == FunctionServiceClient.DEFAULT_MTLS_ENDPOINT - assert FunctionServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert FunctionServiceClient._get_api_endpoint(None, None, default_universe, "always") == FunctionServiceClient.DEFAULT_MTLS_ENDPOINT - assert FunctionServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == FunctionServiceClient.DEFAULT_MTLS_ENDPOINT - assert FunctionServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert FunctionServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - FunctionServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert FunctionServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert FunctionServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert FunctionServiceClient._get_universe_domain(None, None) == FunctionServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - FunctionServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FunctionServiceClient, "grpc"), - (FunctionServiceAsyncClient, "grpc_asyncio"), - (FunctionServiceClient, "rest"), -]) -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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudfunctions.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FunctionServiceGrpcTransport, "grpc"), - (transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FunctionServiceRestTransport, "rest"), -]) -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"), - (FunctionServiceClient, "rest"), -]) -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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudfunctions.googleapis.com' - ) - - -def test_function_service_client_get_transport_class(): - transport = FunctionServiceClient.get_transport_class() - available_transports = [ - transports.FunctionServiceGrpcTransport, - transports.FunctionServiceRestTransport, - ] - 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"), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest"), -]) -@mock.patch.object(FunctionServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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"), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest", "true"), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(FunctionServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - FunctionServiceClient, FunctionServiceAsyncClient -]) -@mock.patch.object(FunctionServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceClient)) -@mock.patch.object(FunctionServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(FunctionServiceAsyncClient)) -def test_function_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = FunctionServiceClient._DEFAULT_UNIVERSE - default_endpoint = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = FunctionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FunctionServiceClient, transports.FunctionServiceGrpcTransport, "grpc"), - (FunctionServiceAsyncClient, transports.FunctionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest"), -]) -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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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), - (FunctionServiceClient, transports.FunctionServiceRestTransport, "rest", None), -]) -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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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', - description='description_value', - state=functions.Function.State.ACTIVE, - environment=functions.Environment.GEN_1, - url='url_value', - kms_key_name='kms_key_name_value', - ) - 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] - request = functions.GetFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.Function) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == functions.Function.State.ACTIVE - assert response.environment == functions.Environment.GEN_1 - assert response.url == 'url_value' - assert response.kms_key_name == 'kms_key_name_value' - - -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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest() - - -def test_get_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GetFunctionRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GetFunctionRequest( - name='name_value', - ) - -def test_get_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_function] = mock_rpc - request = {} - client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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', - description='description_value', - state=functions.Function.State.ACTIVE, - environment=functions.Environment.GEN_1, - url='url_value', - kms_key_name='kms_key_name_value', - )) - response = await 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_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_function] = mock_object - - request = {} - await client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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', - description='description_value', - state=functions.Function.State.ACTIVE, - environment=functions.Environment.GEN_1, - url='url_value', - kms_key_name='kms_key_name_value', - )) - 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] - request = functions.GetFunctionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.Function) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == functions.Function.State.ACTIVE - assert response.environment == functions.Environment.GEN_1 - assert response.url == 'url_value' - assert response.kms_key_name == 'kms_key_name_value' - - -@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] - request = functions.ListFunctionsRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_functions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - - -def test_list_functions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.ListFunctionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_functions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_functions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_functions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_functions] = mock_rpc - request = {} - client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_functions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListFunctionsRequest() - -@pytest.mark.asyncio -async def test_list_functions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_functions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_functions] = mock_object - - request = {} - await client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.ListFunctionsRequest() - assert args[0] == request - - # 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, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_functions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - 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 = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_functions(request={}) - ).pages: - 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] - request = functions.CreateFunctionRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - - -def test_create_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.CreateFunctionRequest( - parent='parent_value', - function_id='function_id_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest( - parent='parent_value', - function_id='function_id_value', - ) - -def test_create_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_function] = mock_rpc - request = {} - client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.CreateFunctionRequest() - -@pytest.mark.asyncio -async def test_create_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_function] = mock_object - - request = {} - await client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.CreateFunctionRequest() - assert args[0] == request - - # 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] - request = functions.UpdateFunctionRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - - -def test_update_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.UpdateFunctionRequest( - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest( - ) - -def test_update_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_function] = mock_rpc - request = {} - client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.UpdateFunctionRequest() - -@pytest.mark.asyncio -async def test_update_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_function] = mock_object - - request = {} - await client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.UpdateFunctionRequest() - assert args[0] == request - - # 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] - request = functions.DeleteFunctionRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_function() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - - -def test_delete_function_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.DeleteFunctionRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_function(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest( - name='name_value', - ) - -def test_delete_function_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_function] = mock_rpc - request = {} - client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_function_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.DeleteFunctionRequest() - -@pytest.mark.asyncio -async def test_delete_function_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_function in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_function] = mock_object - - request = {} - await client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.DeleteFunctionRequest() - assert args[0] == request - - # 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] - request = functions.GenerateUploadUrlRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_upload_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - - -def test_generate_upload_url_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GenerateUploadUrlRequest( - parent='parent_value', - kms_key_name='kms_key_name_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_upload_url(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest( - parent='parent_value', - kms_key_name='kms_key_name_value', - ) - -def test_generate_upload_url_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_upload_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_upload_url] = mock_rpc - request = {} - client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_upload_url_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateUploadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_upload_url_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_upload_url in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.generate_upload_url] = mock_object - - request = {} - await client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.GenerateUploadUrlRequest() - assert args[0] == request - - # 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] - request = functions.GenerateDownloadUrlRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_download_url() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - - -def test_generate_download_url_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.GenerateDownloadUrlRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_download_url(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest( - name='name_value', - ) - -def test_generate_download_url_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_download_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_download_url] = mock_rpc - request = {} - client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_download_url_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.GenerateDownloadUrlRequest() - -@pytest.mark.asyncio -async def test_generate_download_url_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_download_url in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.generate_download_url] = mock_object - - request = {} - await client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.GenerateDownloadUrlRequest() - assert args[0] == request - - # 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] - request = functions.ListRuntimesRequest() - assert args[0] == request - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_runtimes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListRuntimesRequest() - - -def test_list_runtimes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = functions.ListRuntimesRequest( - parent='parent_value', - filter='filter_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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_runtimes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListRuntimesRequest( - parent='parent_value', - filter='filter_value', - ) - -def test_list_runtimes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_runtimes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_runtimes] = mock_rpc - request = {} - client.list_runtimes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_runtimes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_runtimes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == functions.ListRuntimesRequest() - -@pytest.mark.asyncio -async def test_list_runtimes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = FunctionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_runtimes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_runtimes] = mock_object - - request = {} - await client.list_runtimes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_runtimes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@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] - request = functions.ListRuntimesRequest() - assert args[0] == request - - # 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', - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GetFunctionRequest, - dict, -]) -def test_get_function_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.Function( - name='name_value', - description='description_value', - state=functions.Function.State.ACTIVE, - environment=functions.Environment.GEN_1, - url='url_value', - kms_key_name='kms_key_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.Function.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_function(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.Function) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.state == functions.Function.State.ACTIVE - assert response.environment == functions.Environment.GEN_1 - assert response.url == 'url_value' - assert response.kms_key_name == 'kms_key_name_value' - -def test_get_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_function] = mock_rpc - - request = {} - client.get_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_function_rest_required_fields(request_type=functions.GetFunctionRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.Function() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.Function.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_function_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_function_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_get_function") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_get_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GetFunctionRequest.pb(functions.GetFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.Function.to_json(functions.Function()) - - request = functions.GetFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.Function() - - client.get_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_function_rest_bad_request(transport: str = 'rest', request_type=functions.GetFunctionRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_function(request) - - -def test_get_function_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.Function() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.Function.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_get_function_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_function( - functions.GetFunctionRequest(), - name='name_value', - ) - - -def test_get_function_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.ListFunctionsRequest, - dict, -]) -def test_list_functions_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.ListFunctionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.ListFunctionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_functions(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_functions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_functions] = mock_rpc - - request = {} - client.list_functions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_functions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_functions_rest_required_fields(request_type=functions.ListFunctionsRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_functions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_functions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.ListFunctionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.ListFunctionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_functions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_functions_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_functions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_functions_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_list_functions") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_list_functions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.ListFunctionsRequest.pb(functions.ListFunctionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.ListFunctionsResponse.to_json(functions.ListFunctionsResponse()) - - request = functions.ListFunctionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.ListFunctionsResponse() - - client.list_functions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_functions_rest_bad_request(transport: str = 'rest', request_type=functions.ListFunctionsRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_functions(request) - - -def test_list_functions_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.ListFunctionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.ListFunctionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_functions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/locations/*}/functions" % client.transport._host, args[1]) - - -def test_list_functions_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_functions( - functions.ListFunctionsRequest(), - parent='parent_value', - ) - - -def test_list_functions_rest_pager(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - 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(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(functions.ListFunctionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_functions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, functions.Function) - for i in results) - - pages = list(client.list_functions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - functions.CreateFunctionRequest, - dict, -]) -def test_create_function_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["function"] = {'name': 'name_value', 'description': 'description_value', 'build_config': {'build': 'build_value', 'runtime': 'runtime_value', 'entry_point': 'entry_point_value', 'source': {'storage_source': {'bucket': 'bucket_value', 'object_': 'object__value', 'generation': 1068}, 'repo_source': {'branch_name': 'branch_name_value', 'tag_name': 'tag_name_value', 'commit_sha': 'commit_sha_value', 'project_id': 'project_id_value', 'repo_name': 'repo_name_value', 'dir_': 'dir__value', 'invert_regex': True}}, 'source_provenance': {'resolved_storage_source': {}, 'resolved_repo_source': {}}, 'worker_pool': 'worker_pool_value', 'environment_variables': {}, 'docker_registry': 1, 'docker_repository': 'docker_repository_value'}, 'service_config': {'service': 'service_value', 'timeout_seconds': 1621, 'available_memory': 'available_memory_value', 'available_cpu': 'available_cpu_value', 'environment_variables': {}, 'max_instance_count': 1922, 'min_instance_count': 1920, 'vpc_connector': 'vpc_connector_value', 'vpc_connector_egress_settings': 1, 'ingress_settings': 1, 'uri': 'uri_value', 'service_account_email': 'service_account_email_value', 'all_traffic_on_latest_revision': True, 'secret_environment_variables': [{'key': 'key_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'version': 'version_value'}], 'secret_volumes': [{'mount_path': 'mount_path_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'versions': [{'version': 'version_value', 'path': 'path_value'}]}], 'revision': 'revision_value', 'max_instance_request_concurrency': 3436, 'security_level': 1}, 'event_trigger': {'trigger': 'trigger_value', 'trigger_region': 'trigger_region_value', 'event_type': 'event_type_value', 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'pubsub_topic': 'pubsub_topic_value', 'service_account_email': 'service_account_email_value', 'retry_policy': 1, 'channel': 'channel_value'}, 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'labels': {}, 'state_messages': [{'severity': 1, 'type_': 'type__value', 'message': 'message_value'}], 'environment': 1, 'url': 'url_value', 'kms_key_name': 'kms_key_name_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = functions.CreateFunctionRequest.meta.fields["function"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["function"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["function"][field])): - del request_init["function"][field][i][subfield] - else: - del request_init["function"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_create_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_function] = mock_rpc - - request = {} - client.create_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_function_rest_required_fields(request_type=functions.CreateFunctionRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_function._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("function_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_function_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(("functionId", )) & set(("parent", "function", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_function_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_create_function") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_create_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.CreateFunctionRequest.pb(functions.CreateFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.CreateFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_function_rest_bad_request(transport: str = 'rest', request_type=functions.CreateFunctionRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_function(request) - - -def test_create_function_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/locations/*}/functions" % client.transport._host, args[1]) - - -def test_create_function_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_function( - functions.CreateFunctionRequest(), - parent='parent_value', - function=functions.Function(name='name_value'), - function_id='function_id_value', - ) - - -def test_create_function_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.UpdateFunctionRequest, - dict, -]) -def test_update_function_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - request_init["function"] = {'name': 'projects/sample1/locations/sample2/functions/sample3', 'description': 'description_value', 'build_config': {'build': 'build_value', 'runtime': 'runtime_value', 'entry_point': 'entry_point_value', 'source': {'storage_source': {'bucket': 'bucket_value', 'object_': 'object__value', 'generation': 1068}, 'repo_source': {'branch_name': 'branch_name_value', 'tag_name': 'tag_name_value', 'commit_sha': 'commit_sha_value', 'project_id': 'project_id_value', 'repo_name': 'repo_name_value', 'dir_': 'dir__value', 'invert_regex': True}}, 'source_provenance': {'resolved_storage_source': {}, 'resolved_repo_source': {}}, 'worker_pool': 'worker_pool_value', 'environment_variables': {}, 'docker_registry': 1, 'docker_repository': 'docker_repository_value'}, 'service_config': {'service': 'service_value', 'timeout_seconds': 1621, 'available_memory': 'available_memory_value', 'available_cpu': 'available_cpu_value', 'environment_variables': {}, 'max_instance_count': 1922, 'min_instance_count': 1920, 'vpc_connector': 'vpc_connector_value', 'vpc_connector_egress_settings': 1, 'ingress_settings': 1, 'uri': 'uri_value', 'service_account_email': 'service_account_email_value', 'all_traffic_on_latest_revision': True, 'secret_environment_variables': [{'key': 'key_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'version': 'version_value'}], 'secret_volumes': [{'mount_path': 'mount_path_value', 'project_id': 'project_id_value', 'secret': 'secret_value', 'versions': [{'version': 'version_value', 'path': 'path_value'}]}], 'revision': 'revision_value', 'max_instance_request_concurrency': 3436, 'security_level': 1}, 'event_trigger': {'trigger': 'trigger_value', 'trigger_region': 'trigger_region_value', 'event_type': 'event_type_value', 'event_filters': [{'attribute': 'attribute_value', 'value': 'value_value', 'operator': 'operator_value'}], 'pubsub_topic': 'pubsub_topic_value', 'service_account_email': 'service_account_email_value', 'retry_policy': 1, 'channel': 'channel_value'}, 'state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'labels': {}, 'state_messages': [{'severity': 1, 'type_': 'type__value', 'message': 'message_value'}], 'environment': 1, 'url': 'url_value', 'kms_key_name': 'kms_key_name_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = functions.UpdateFunctionRequest.meta.fields["function"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["function"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["function"][field])): - del request_init["function"][field][i][subfield] - else: - del request_init["function"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_update_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_function] = mock_rpc - - request = {} - client.update_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_function_rest_required_fields(request_type=functions.UpdateFunctionRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_function._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_function_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("function", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_function_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_update_function") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_update_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.UpdateFunctionRequest.pb(functions.UpdateFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.UpdateFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_function_rest_bad_request(transport: str = 'rest', request_type=functions.UpdateFunctionRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_function(request) - - -def test_update_function_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'function': {'name': 'projects/sample1/locations/sample2/functions/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{function.name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_update_function_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_function( - functions.UpdateFunctionRequest(), - function=functions.Function(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_function_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.DeleteFunctionRequest, - dict, -]) -def test_delete_function_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_function(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_delete_function_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_function in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_function] = mock_rpc - - request = {} - client.delete_function(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_function(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_function_rest_required_fields(request_type=functions.DeleteFunctionRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_function._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_function(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_function_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_function._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_function_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_delete_function") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_delete_function") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.DeleteFunctionRequest.pb(functions.DeleteFunctionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = functions.DeleteFunctionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_function(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_function_rest_bad_request(transport: str = 'rest', request_type=functions.DeleteFunctionRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_function(request) - - -def test_delete_function_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_function(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=projects/*/locations/*/functions/*}" % client.transport._host, args[1]) - - -def test_delete_function_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_function( - functions.DeleteFunctionRequest(), - name='name_value', - ) - - -def test_delete_function_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateUploadUrlRequest, - dict, -]) -def test_generate_upload_url_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.GenerateUploadUrlResponse( - upload_url='upload_url_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.GenerateUploadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_upload_url(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_upload_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_upload_url] = mock_rpc - - request = {} - client.generate_upload_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_upload_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_upload_url_rest_required_fields(request_type=functions.GenerateUploadUrlRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_upload_url._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_upload_url._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.GenerateUploadUrlResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.GenerateUploadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_upload_url(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_upload_url_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_upload_url._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_upload_url_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_generate_upload_url") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_generate_upload_url") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GenerateUploadUrlRequest.pb(functions.GenerateUploadUrlRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.GenerateUploadUrlResponse.to_json(functions.GenerateUploadUrlResponse()) - - request = functions.GenerateUploadUrlRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.GenerateUploadUrlResponse() - - client.generate_upload_url(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_upload_url_rest_bad_request(transport: str = 'rest', request_type=functions.GenerateUploadUrlRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_upload_url(request) - - -def test_generate_upload_url_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.GenerateDownloadUrlRequest, - dict, -]) -def test_generate_download_url_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.GenerateDownloadUrlResponse( - download_url='download_url_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.GenerateDownloadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_download_url(request) - - # 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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_download_url in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_download_url] = mock_rpc - - request = {} - client.generate_download_url(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_download_url(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_download_url_rest_required_fields(request_type=functions.GenerateDownloadUrlRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_download_url._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_download_url._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.GenerateDownloadUrlResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.GenerateDownloadUrlResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_download_url(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_download_url_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_download_url._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_download_url_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_generate_download_url") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_generate_download_url") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.GenerateDownloadUrlRequest.pb(functions.GenerateDownloadUrlRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.GenerateDownloadUrlResponse.to_json(functions.GenerateDownloadUrlResponse()) - - request = functions.GenerateDownloadUrlRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.GenerateDownloadUrlResponse() - - client.generate_download_url(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_download_url_rest_bad_request(transport: str = 'rest', request_type=functions.GenerateDownloadUrlRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_download_url(request) - - -def test_generate_download_url_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - functions.ListRuntimesRequest, - dict, -]) -def test_list_runtimes_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.ListRuntimesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.ListRuntimesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_runtimes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, functions.ListRuntimesResponse) - -def test_list_runtimes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_runtimes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_runtimes] = mock_rpc - - request = {} - client.list_runtimes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_runtimes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_runtimes_rest_required_fields(request_type=functions.ListRuntimesRequest): - transport_class = transports.FunctionServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_runtimes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_runtimes._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = functions.ListRuntimesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = functions.ListRuntimesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_runtimes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_runtimes_rest_unset_required_fields(): - transport = transports.FunctionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_runtimes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_runtimes_rest_interceptors(null_interceptor): - transport = transports.FunctionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FunctionServiceRestInterceptor(), - ) - client = FunctionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "post_list_runtimes") as post, \ - mock.patch.object(transports.FunctionServiceRestInterceptor, "pre_list_runtimes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = functions.ListRuntimesRequest.pb(functions.ListRuntimesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = functions.ListRuntimesResponse.to_json(functions.ListRuntimesResponse()) - - request = functions.ListRuntimesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = functions.ListRuntimesResponse() - - client.list_runtimes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_runtimes_rest_bad_request(transport: str = 'rest', request_type=functions.ListRuntimesRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_runtimes(request) - - -def test_list_runtimes_rest_flattened(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = functions.ListRuntimesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = functions.ListRuntimesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_runtimes(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=projects/*/locations/*}/runtimes" % client.transport._host, args[1]) - - -def test_list_runtimes_rest_flattened_error(transport: str = 'rest'): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_runtimes( - functions.ListRuntimesRequest(), - parent='parent_value', - ) - - -def test_list_runtimes_rest_error(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 = client_options.ClientOptions() - 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, - transports.FunctionServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = 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, - transports.FunctionServiceRestTransport, - ], -) -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 - ) - -def test_function_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.FunctionServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_function_service_rest_lro_client(): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudfunctions.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudfunctions.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_function_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FunctionServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FunctionServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_function._session - session2 = client2.transport.get_function._session - assert session1 != session2 - session1 = client1.transport.list_functions._session - session2 = client2.transport.list_functions._session - assert session1 != session2 - session1 = client1.transport.create_function._session - session2 = client2.transport.create_function._session - assert session1 != session2 - session1 = client1.transport.update_function._session - session2 = client2.transport.update_function._session - assert session1 != session2 - session1 = client1.transport.delete_function._session - session2 = client2.transport.delete_function._session - assert session1 != session2 - session1 = client1.transport.generate_upload_url._session - session2 = client2.transport.generate_upload_url._session - assert session1 != session2 - session1 = client1.transport.generate_download_url._session - session2 = client2.transport.generate_download_url._session - assert session1 != session2 - session1 = client1.transport.list_runtimes._session - session2 = client2.transport.list_runtimes._session - assert session1 != session2 -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_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = FunctionServiceClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "crypto_key": "clam", - } - path = FunctionServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = FunctionServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_function_path(): - project = "whelk" - location = "octopus" - function = "oyster" - 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": "nudibranch", - "location": "cuttlefish", - "function": "mussel", - } - 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 = "winkle" - location = "nautilus" - repository = "scallop" - 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": "abalone", - "location": "squid", - "repository": "clam", - } - 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 = "whelk" - location = "octopus" - service = "oyster" - 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": "nudibranch", - "location": "cuttlefish", - "service": "mussel", - } - 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 = "winkle" - topic = "nautilus" - 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": "scallop", - "topic": "abalone", - } - 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 = "squid" - location = "clam" - trigger = "whelk" - 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": "octopus", - "location": "oyster", - "trigger": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - worker_pool = "winkle" - 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": "nautilus", - "location": "scallop", - "worker_pool": "abalone", - } - 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 = "squid" - 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": "clam", - } - 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 = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = FunctionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - 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 = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FunctionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - 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 = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = FunctionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - 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 = "winkle" - location = "nautilus" - 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": "scallop", - "location": "abalone", - } - 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_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/functions/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/functions/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/functions/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/functions/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = FunctionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_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_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 = 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_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 = 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_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 = 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 = { - "rest": "_session", - "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 = [ - 'rest', - '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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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, - ) diff --git a/packages/google-cloud-functions/google/cloud/functions/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions/gapic_version.py index d837bed725c9..558c8aab67c5 100644 --- a/packages/google-cloud-functions/google/cloud/functions/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py index d837bed725c9..558c8aab67c5 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/types/functions.py b/packages/google-cloud-functions/google/cloud/functions_v1/types/functions.py index c7083cf71640..38246cfb280c 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/types/functions.py +++ b/packages/google-cloud-functions/google/cloud/functions_v1/types/functions.py @@ -267,14 +267,14 @@ class CloudFunction(proto.Message): function sources. Disclaimer: This field is only supported for Firebase function deployments. docker_repository (str): - User managed repository created in Artifact Registry - optionally with a customer managed encryption key. If - specified, deployments will use Artifact Registry. If - unspecified and the deployment is eligible to use Artifact - Registry, GCF will create and use a repository named - 'gcf-artifacts' for every deployed region. This is the - repository to which the function docker image will be pushed - after it is built by Cloud Build. + User-managed repository created in Artifact Registry to + which the function's Docker image will be pushed after it is + built by Cloud Build. May optionally be encrypted with a + customer-managed encryption key (CMEK). If unspecified and + ``docker_registry`` is not explicitly set to + ``CONTAINER_REGISTRY``, GCF will create and use a default + Artifact Registry repository named 'gcf-artifacts' in the + region. It must match the pattern ``projects/{project}/locations/{location}/repositories/{repository}``. @@ -289,15 +289,15 @@ class CloudFunction(proto.Message): ``docker_repository`` field is specified, this field should either be left unspecified or set to ``ARTIFACT_REGISTRY``. automatic_update_policy (google.cloud.functions_v1.types.CloudFunction.AutomaticUpdatePolicy): - See the comment next to this message for more - details. This field is a member of `oneof`_ ``runtime_update_policy``. on_deploy_update_policy (google.cloud.functions_v1.types.CloudFunction.OnDeployUpdatePolicy): - See the comment next to this message for more - details. This field is a member of `oneof`_ ``runtime_update_policy``. + build_service_account (str): + A service account the user provides for use with Cloud + Build. The format of this field is + ``projects/{projectId}/serviceAccounts/{serviceAccountEmail}``. """ class VpcConnectorEgressSettings(proto.Enum): @@ -378,7 +378,7 @@ class OnDeployUpdatePolicy(proto.Message): Attributes: runtime_version (str): - Output only. contains the runtime version + Output only. Contains the runtime version which was used during latest function deployment. """ @@ -551,6 +551,10 @@ class OnDeployUpdatePolicy(proto.Message): oneof="runtime_update_policy", message=OnDeployUpdatePolicy, ) + build_service_account: str = proto.Field( + proto.STRING, + number=43, + ) class SourceRepository(proto.Message): @@ -572,7 +576,8 @@ class SourceRepository(proto.Message): ``https://source.developers.google.com/projects/*/repos/*/fixed-aliases/*/paths/*`` You may omit ``paths/*`` if you want to use the main - directory. + directory. The function response may add an empty + ``/paths/`` to the URL. deployed_url (str): Output only. The URL pointing to the hosted repository where the function were defined at @@ -596,7 +601,7 @@ class HttpsTrigger(proto.Message): Attributes: url (str): - Output only. The deployed URL for the + Output only. The deployed url for the function. security_level (google.cloud.functions_v1.types.HttpsTrigger.SecurityLevel): The security level for the function. diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py index d837bed725c9..558c8aab67c5 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json index 287bc8731e37..3a16e5fca57c 100644 --- a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json +++ b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-functions", - "version": "1.16.5" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json index 7a5cb30e0675..0dbb0a2efac1 100644 --- a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json +++ b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-functions", - "version": "1.16.5" + "version": "0.1.0" }, "snippets": [ { 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 9369954ae899..6f12c5294265 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 @@ -1731,6 +1731,7 @@ def test_get_function(request_type, transport: str = "grpc"): source_token="source_token_value", docker_repository="docker_repository_value", docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + build_service_account="build_service_account_value", source_archive_url="source_archive_url_value", ) response = client.get_function(request) @@ -1772,6 +1773,7 @@ def test_get_function(request_type, transport: str = "grpc"): response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY ) + assert response.build_service_account == "build_service_account_value" def test_get_function_empty_call(): @@ -1891,6 +1893,7 @@ async def test_get_function_empty_call_async(): source_token="source_token_value", docker_repository="docker_repository_value", docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + build_service_account="build_service_account_value", ) ) response = await client.get_function() @@ -1979,6 +1982,7 @@ async def test_get_function_async( source_token="source_token_value", docker_repository="docker_repository_value", docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + build_service_account="build_service_account_value", ) ) response = await client.get_function(request) @@ -2020,6 +2024,7 @@ async def test_get_function_async( response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY ) + assert response.build_service_account == "build_service_account_value" @pytest.mark.asyncio @@ -5442,6 +5447,7 @@ def test_get_function_rest(request_type): source_token="source_token_value", docker_repository="docker_repository_value", docker_registry=functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY, + build_service_account="build_service_account_value", source_archive_url="source_archive_url_value", ) @@ -5487,6 +5493,7 @@ def test_get_function_rest(request_type): response.docker_registry == functions.CloudFunction.DockerRegistry.CONTAINER_REGISTRY ) + assert response.build_service_account == "build_service_account_value" def test_get_function_rest_use_cached_wrapped_rpc(): @@ -5821,6 +5828,7 @@ def test_create_function_rest(request_type): "docker_registry": 1, "automatic_update_policy": {}, "on_deploy_update_policy": {"runtime_version": "runtime_version_value"}, + "build_service_account": "build_service_account_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6256,6 +6264,7 @@ def test_update_function_rest(request_type): "docker_registry": 1, "automatic_update_policy": {}, "on_deploy_update_policy": {"runtime_version": "runtime_version_value"}, + "build_service_account": "build_service_account_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency