From fc86b643e789a1b52689cdb4267831f493822afe Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 30 Oct 2023 17:49:35 +0000 Subject: [PATCH] chore(python): Update build rules for google/cloud/gkehub/v1/configmanagement chore(python): Update build rules for google/cloud/gkehub/v1/multiclusteringress chore(python): Update build rules for google/cloud/gkehub/v1 PiperOrigin-RevId: 577855184 Source-Link: https://github.com/googleapis/googleapis/commit/5ca19108a3251b1cb8dd5b246b37ce2eed2dc92f Source-Link: https://github.com/googleapis/googleapis-gen/commit/90eea5bcc5b893c0252eabdbee23c552ead13ee7 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiOTBlZWE1YmNjNWI4OTNjMDI1MmVhYmRiZWUyM2M1NTJlYWQxM2VlNyJ9 --- owl-bot-staging/v1/.coveragerc | 13 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../v1/configmanagement/.coveragerc | 13 + owl-bot-staging/v1/configmanagement/.flake8 | 33 + .../v1/configmanagement/MANIFEST.in | 2 + .../v1/configmanagement/README.rst | 49 + .../configmanagement/docs/_static/custom.css | 3 + .../v1/configmanagement/docs/conf.py | 376 + .../docs/configmanagement_v1/services_.rst | 4 + .../docs/configmanagement_v1/types_.rst | 6 + .../v1/configmanagement/docs/index.rst | 7 + .../cloud/gkehub/configmanagement/__init__.py | 67 + .../gkehub/configmanagement/gapic_version.py | 16 + .../cloud/gkehub/configmanagement/py.typed | 2 + .../gkehub/configmanagement_v1/__init__.py | 68 + .../configmanagement_v1/gapic_metadata.json | 7 + .../configmanagement_v1/gapic_version.py | 16 + .../cloud/gkehub/configmanagement_v1/py.typed | 2 + .../configmanagement_v1/services/__init__.py | 15 + .../configmanagement_v1/types/__init__.py | 64 + .../types/configmanagement.py | 833 ++ owl-bot-staging/v1/configmanagement/mypy.ini | 3 + .../v1/configmanagement/noxfile.py | 184 + .../fixup_configmanagement_v1_keywords.py | 175 + owl-bot-staging/v1/configmanagement/setup.py | 90 + .../testing/constraints-3.10.txt | 6 + .../testing/constraints-3.11.txt | 6 + .../testing/constraints-3.12.txt | 6 + .../testing/constraints-3.7.txt | 9 + .../testing/constraints-3.8.txt | 6 + .../testing/constraints-3.9.txt | 6 + .../v1/configmanagement/tests/__init__.py | 16 + .../configmanagement/tests/unit/__init__.py | 16 + .../tests/unit/gapic/__init__.py | 16 + .../gapic/configmanagement_v1/__init__.py | 16 + owl-bot-staging/v1/docs/_static/custom.css | 3 + owl-bot-staging/v1/docs/conf.py | 376 + owl-bot-staging/v1/docs/gkehub_v1/gke_hub.rst | 10 + .../v1/docs/gkehub_v1/services_.rst | 6 + owl-bot-staging/v1/docs/gkehub_v1/types_.rst | 6 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/gkehub/__init__.py | 95 + .../v1/google/cloud/gkehub/gapic_version.py | 16 + .../v1/google/cloud/gkehub/py.typed | 2 + .../v1/google/cloud/gkehub_v1/__init__.py | 96 + .../cloud/gkehub_v1/gapic_metadata.json | 193 + .../google/cloud/gkehub_v1/gapic_version.py | 16 + .../v1/google/cloud/gkehub_v1/py.typed | 2 + .../cloud/gkehub_v1/services/__init__.py | 15 + .../gkehub_v1/services/gke_hub/__init__.py | 22 + .../services/gke_hub/async_client.py | 1542 ++++ .../gkehub_v1/services/gke_hub/client.py | 1756 +++++ .../gkehub_v1/services/gke_hub/pagers.py | 262 + .../services/gke_hub/transports/__init__.py | 38 + .../services/gke_hub/transports/base.py | 297 + .../services/gke_hub/transports/grpc.py | 573 ++ .../gke_hub/transports/grpc_asyncio.py | 572 ++ .../services/gke_hub/transports/rest.py | 1472 ++++ .../google/cloud/gkehub_v1/types/__init__.py | 92 + .../google/cloud/gkehub_v1/types/feature.py | 358 + .../cloud/gkehub_v1/types/membership.py | 605 ++ .../google/cloud/gkehub_v1/types/service.py | 800 ++ .../v1/multiclusteringress/.coveragerc | 13 + .../v1/multiclusteringress/.flake8 | 33 + .../v1/multiclusteringress/MANIFEST.in | 2 + .../v1/multiclusteringress/README.rst | 49 + .../docs/_static/custom.css | 3 + .../v1/multiclusteringress/docs/conf.py | 376 + .../v1/multiclusteringress/docs/index.rst | 7 + .../docs/multiclusteringress_v1/services_.rst | 4 + .../docs/multiclusteringress_v1/types_.rst | 6 + .../gkehub/multiclusteringress/__init__.py | 25 + .../multiclusteringress/gapic_version.py | 16 + .../cloud/gkehub/multiclusteringress/py.typed | 2 + .../gkehub/multiclusteringress_v1/__init__.py | 26 + .../gapic_metadata.json | 7 + .../multiclusteringress_v1/gapic_version.py | 16 + .../gkehub/multiclusteringress_v1/py.typed | 2 + .../services/__init__.py | 15 + .../multiclusteringress_v1/types/__init__.py | 22 + .../types/multiclusteringress.py | 48 + .../v1/multiclusteringress/mypy.ini | 3 + .../v1/multiclusteringress/noxfile.py | 184 + .../fixup_multiclusteringress_v1_keywords.py | 175 + .../v1/multiclusteringress/setup.py | 90 + .../testing/constraints-3.10.txt | 6 + .../testing/constraints-3.11.txt | 6 + .../testing/constraints-3.12.txt | 6 + .../testing/constraints-3.7.txt | 9 + .../testing/constraints-3.8.txt | 6 + .../testing/constraints-3.9.txt | 6 + .../v1/multiclusteringress/tests/__init__.py | 16 + .../tests/unit/__init__.py | 16 + .../tests/unit/gapic/__init__.py | 16 + .../gapic/multiclusteringress_v1/__init__.py | 16 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ..._generated_gke_hub_create_feature_async.py | 55 + ...1_generated_gke_hub_create_feature_sync.py | 55 + ...nerated_gke_hub_create_membership_async.py | 57 + ...enerated_gke_hub_create_membership_sync.py | 57 + ..._generated_gke_hub_delete_feature_async.py | 55 + ...1_generated_gke_hub_delete_feature_sync.py | 55 + ...nerated_gke_hub_delete_membership_async.py | 56 + ...enerated_gke_hub_delete_membership_sync.py | 56 + ...gke_hub_generate_connect_manifest_async.py | 52 + ..._gke_hub_generate_connect_manifest_sync.py | 52 + ..._v1_generated_gke_hub_get_feature_async.py | 51 + ...b_v1_generated_gke_hub_get_feature_sync.py | 51 + ..._generated_gke_hub_get_membership_async.py | 52 + ...1_generated_gke_hub_get_membership_sync.py | 52 + ...1_generated_gke_hub_list_features_async.py | 52 + ...v1_generated_gke_hub_list_features_sync.py | 52 + ...enerated_gke_hub_list_memberships_async.py | 53 + ...generated_gke_hub_list_memberships_sync.py | 53 + ..._generated_gke_hub_update_feature_async.py | 55 + ...1_generated_gke_hub_update_feature_sync.py | 55 + ...nerated_gke_hub_update_membership_async.py | 56 + ...enerated_gke_hub_update_membership_sync.py | 56 + ...ippet_metadata_google.cloud.gkehub.v1.json | 1842 +++++ .../v1/scripts/fixup_gkehub_v1_keywords.py | 186 + owl-bot-staging/v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/gkehub_v1/__init__.py | 16 + .../unit/gapic/gkehub_v1/test_gke_hub.py | 6795 +++++++++++++++++ owl-bot-staging/v1beta1/.coveragerc | 13 + owl-bot-staging/v1beta1/.flake8 | 33 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + .../v1beta1/docs/_static/custom.css | 3 + owl-bot-staging/v1beta1/docs/conf.py | 376 + .../gke_hub_membership_service.rst | 10 + .../v1beta1/docs/gkehub_v1beta1/services_.rst | 6 + .../v1beta1/docs/gkehub_v1beta1/types_.rst | 6 + owl-bot-staging/v1beta1/docs/index.rst | 7 + .../v1beta1/google/cloud/gkehub/__init__.py | 87 + .../google/cloud/gkehub/gapic_version.py | 16 + .../v1beta1/google/cloud/gkehub/py.typed | 2 + .../google/cloud/gkehub_v1beta1/__init__.py | 88 + .../cloud/gkehub_v1beta1/gapic_metadata.json | 148 + .../cloud/gkehub_v1beta1/gapic_version.py | 16 + .../google/cloud/gkehub_v1beta1/py.typed | 2 + .../cloud/gkehub_v1beta1/services/__init__.py | 15 + .../gke_hub_membership_service/__init__.py | 22 + .../async_client.py | 1720 +++++ .../gke_hub_membership_service/client.py | 1922 +++++ .../gke_hub_membership_service/pagers.py | 139 + .../transports/__init__.py | 38 + .../transports/base.py | 338 + .../transports/grpc.py | 692 ++ .../transports/grpc_asyncio.py | 691 ++ .../transports/rest.py | 1930 +++++ .../cloud/gkehub_v1beta1/types/__init__.py | 80 + .../cloud/gkehub_v1beta1/types/membership.py | 1470 ++++ owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 184 + ...bership_service_create_membership_async.py | 57 + ...mbership_service_create_membership_sync.py | 57 + ...bership_service_delete_membership_async.py | 56 + ...mbership_service_delete_membership_sync.py | 56 + ...service_generate_connect_manifest_async.py | 52 + ..._service_generate_connect_manifest_sync.py | 52 + ...ice_generate_exclusivity_manifest_async.py | 52 + ...vice_generate_exclusivity_manifest_sync.py | 52 + ...membership_service_get_membership_async.py | 52 + ..._membership_service_get_membership_sync.py | 52 + ...mbership_service_list_memberships_async.py | 53 + ...embership_service_list_memberships_sync.py | 53 + ...bership_service_update_membership_async.py | 56 + ...mbership_service_update_membership_sync.py | 56 + ...ship_service_validate_exclusivity_async.py | 53 + ...rship_service_validate_exclusivity_sync.py | 53 + ..._metadata_google.cloud.gkehub.v1beta1.json | 1311 ++++ .../scripts/fixup_gkehub_v1beta1_keywords.py | 183 + owl-bot-staging/v1beta1/setup.py | 91 + .../v1beta1/testing/constraints-3.10.txt | 7 + .../v1beta1/testing/constraints-3.11.txt | 7 + .../v1beta1/testing/constraints-3.12.txt | 7 + .../v1beta1/testing/constraints-3.7.txt | 10 + .../v1beta1/testing/constraints-3.8.txt | 7 + .../v1beta1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/gkehub_v1beta1/__init__.py | 16 + .../test_gke_hub_membership_service.py | 6779 ++++++++++++++++ 196 files changed, 42528 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/configmanagement/.coveragerc create mode 100644 owl-bot-staging/v1/configmanagement/.flake8 create mode 100644 owl-bot-staging/v1/configmanagement/MANIFEST.in create mode 100644 owl-bot-staging/v1/configmanagement/README.rst create mode 100644 owl-bot-staging/v1/configmanagement/docs/_static/custom.css create mode 100644 owl-bot-staging/v1/configmanagement/docs/conf.py create mode 100644 owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/services_.rst create mode 100644 owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/types_.rst create mode 100644 owl-bot-staging/v1/configmanagement/docs/index.rst create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/gapic_version.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/py.typed create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/py.typed create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/configmanagement.py create mode 100644 owl-bot-staging/v1/configmanagement/mypy.ini create mode 100644 owl-bot-staging/v1/configmanagement/noxfile.py create mode 100644 owl-bot-staging/v1/configmanagement/scripts/fixup_configmanagement_v1_keywords.py create mode 100644 owl-bot-staging/v1/configmanagement/setup.py create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/configmanagement/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/configmanagement/tests/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/configmanagement/tests/unit/gapic/configmanagement_v1/__init__.py create mode 100644 owl-bot-staging/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/gkehub_v1/gke_hub.rst create mode 100644 owl-bot-staging/v1/docs/gkehub_v1/services_.rst create mode 100644 owl-bot-staging/v1/docs/gkehub_v1/types_.rst create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/gkehub/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/client.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/types/feature.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/types/membership.py create mode 100644 owl-bot-staging/v1/google/cloud/gkehub_v1/types/service.py create mode 100644 owl-bot-staging/v1/multiclusteringress/.coveragerc create mode 100644 owl-bot-staging/v1/multiclusteringress/.flake8 create mode 100644 owl-bot-staging/v1/multiclusteringress/MANIFEST.in create mode 100644 owl-bot-staging/v1/multiclusteringress/README.rst create mode 100644 owl-bot-staging/v1/multiclusteringress/docs/_static/custom.css create mode 100644 owl-bot-staging/v1/multiclusteringress/docs/conf.py create mode 100644 owl-bot-staging/v1/multiclusteringress/docs/index.rst create mode 100644 owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/services_.rst create mode 100644 owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/types_.rst create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/gapic_version.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/py.typed create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/py.typed create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/multiclusteringress.py create mode 100644 owl-bot-staging/v1/multiclusteringress/mypy.ini create mode 100644 owl-bot-staging/v1/multiclusteringress/noxfile.py create mode 100644 owl-bot-staging/v1/multiclusteringress/scripts/fixup_multiclusteringress_v1_keywords.py create mode 100644 owl-bot-staging/v1/multiclusteringress/setup.py create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/multiclusteringress/tests/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/multiclusteringress_v1/__init__.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_gkehub_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/test_gke_hub.py create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/.flake8 create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/gkehub_v1beta1/gke_hub_membership_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/gkehub_v1beta1/services_.rst create mode 100644 owl-bot-staging/v1beta1/docs/gkehub_v1beta1/types_.rst create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub/gapic_version.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/membership.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_gkehub_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..2653a96 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/gkehub/__init__.py + google/cloud/gkehub/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/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- 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/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..e220dcb --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/gkehub *.py +recursive-include google/cloud/gkehub_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..00b883a --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Gkehub 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 Gkehub 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/v1/configmanagement/.coveragerc b/owl-bot-staging/v1/configmanagement/.coveragerc new file mode 100644 index 0000000..30a6c30 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/gkehub/configmanagement/__init__.py + google/cloud/gkehub/configmanagement/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/v1/configmanagement/.flake8 b/owl-bot-staging/v1/configmanagement/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/.flake8 @@ -0,0 +1,33 @@ +# -*- 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/v1/configmanagement/MANIFEST.in b/owl-bot-staging/v1/configmanagement/MANIFEST.in new file mode 100644 index 0000000..d57dfae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/gkehub/configmanagement *.py +recursive-include google/cloud/gkehub/configmanagement_v1 *.py diff --git a/owl-bot-staging/v1/configmanagement/README.rst b/owl-bot-staging/v1/configmanagement/README.rst new file mode 100644 index 0000000..3e895f1 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Gkehub Configmanagement 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 Gkehub Configmanagement 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/v1/configmanagement/docs/_static/custom.css b/owl-bot-staging/v1/configmanagement/docs/_static/custom.css new file mode 100644 index 0000000..06423be --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1/configmanagement/docs/conf.py b/owl-bot-staging/v1/configmanagement/docs/conf.py new file mode 100644 index 0000000..d6d4d3d --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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-gkehub-configmanagement 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-gkehub-configmanagement" +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 Gkehub 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-gkehub-configmanagement-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-gkehub-configmanagement.tex", + u"google-cloud-gkehub-configmanagement 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-gkehub-configmanagement", + u"Google Cloud Gkehub Configmanagement 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-gkehub-configmanagement", + u"google-cloud-gkehub-configmanagement Documentation", + author, + "google-cloud-gkehub-configmanagement", + "GAPIC library for Google Cloud Gkehub Configmanagement 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/v1/configmanagement/docs/configmanagement_v1/services_.rst b/owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/services_.rst new file mode 100644 index 0000000..6e2fc7d --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/services_.rst @@ -0,0 +1,4 @@ +Services for Google Cloud Gkehub Configmanagement v1 API +======================================================== +.. toctree:: + :maxdepth: 2 diff --git a/owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/types_.rst b/owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/types_.rst new file mode 100644 index 0000000..cead981 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/docs/configmanagement_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gkehub Configmanagement v1 API +===================================================== + +.. automodule:: google.cloud.gkehub.configmanagement_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/configmanagement/docs/index.rst b/owl-bot-staging/v1/configmanagement/docs/index.rst new file mode 100644 index 0000000..08bb16f --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + configmanagement_v1/services + configmanagement_v1/types diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/__init__.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/__init__.py new file mode 100644 index 0000000..85000a5 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/__init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub.configmanagement import gapic_version as package_version + +__version__ = package_version.__version__ + + + +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import ConfigSync +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import ConfigSyncDeploymentState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import ConfigSyncState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import ConfigSyncVersion +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import ErrorResource +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import GatekeeperDeploymentState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import GitConfig +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import GroupVersionKind +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import HierarchyControllerConfig +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import HierarchyControllerDeploymentState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import HierarchyControllerState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import HierarchyControllerVersion +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import InstallError +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import MembershipSpec +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import MembershipState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import OperatorState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import PolicyController +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import PolicyControllerState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import PolicyControllerVersion +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import SyncError +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import SyncState +from google.cloud.gkehub.configmanagement_v1.types.configmanagement import DeploymentState + +__all__ = ('ConfigSync', + 'ConfigSyncDeploymentState', + 'ConfigSyncState', + 'ConfigSyncVersion', + 'ErrorResource', + 'GatekeeperDeploymentState', + 'GitConfig', + 'GroupVersionKind', + 'HierarchyControllerConfig', + 'HierarchyControllerDeploymentState', + 'HierarchyControllerState', + 'HierarchyControllerVersion', + 'InstallError', + 'MembershipSpec', + 'MembershipState', + 'OperatorState', + 'PolicyController', + 'PolicyControllerState', + 'PolicyControllerVersion', + 'SyncError', + 'SyncState', + 'DeploymentState', +) diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/gapic_version.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/google/cloud/gkehub/configmanagement/py.typed b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/py.typed new file mode 100644 index 0000000..5d21684 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gkehub-configmanagement package uses inline types. diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/__init__.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/__init__.py new file mode 100644 index 0000000..6873043 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/__init__.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub.configmanagement_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + + +from .types.configmanagement import ConfigSync +from .types.configmanagement import ConfigSyncDeploymentState +from .types.configmanagement import ConfigSyncState +from .types.configmanagement import ConfigSyncVersion +from .types.configmanagement import ErrorResource +from .types.configmanagement import GatekeeperDeploymentState +from .types.configmanagement import GitConfig +from .types.configmanagement import GroupVersionKind +from .types.configmanagement import HierarchyControllerConfig +from .types.configmanagement import HierarchyControllerDeploymentState +from .types.configmanagement import HierarchyControllerState +from .types.configmanagement import HierarchyControllerVersion +from .types.configmanagement import InstallError +from .types.configmanagement import MembershipSpec +from .types.configmanagement import MembershipState +from .types.configmanagement import OperatorState +from .types.configmanagement import PolicyController +from .types.configmanagement import PolicyControllerState +from .types.configmanagement import PolicyControllerVersion +from .types.configmanagement import SyncError +from .types.configmanagement import SyncState +from .types.configmanagement import DeploymentState + +__all__ = ( +'ConfigSync', +'ConfigSyncDeploymentState', +'ConfigSyncState', +'ConfigSyncVersion', +'DeploymentState', +'ErrorResource', +'GatekeeperDeploymentState', +'GitConfig', +'GroupVersionKind', +'HierarchyControllerConfig', +'HierarchyControllerDeploymentState', +'HierarchyControllerState', +'HierarchyControllerVersion', +'InstallError', +'MembershipSpec', +'MembershipState', +'OperatorState', +'PolicyController', +'PolicyControllerState', +'PolicyControllerVersion', +'SyncError', +'SyncState', +) diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_metadata.json b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_metadata.json new file mode 100644 index 0000000..4cbd386 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_metadata.json @@ -0,0 +1,7 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gkehub.configmanagement_v1", + "protoPackage": "google.cloud.gkehub.configmanagement.v1", + "schema": "1.0" +} diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_version.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/py.typed b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/py.typed new file mode 100644 index 0000000..5d21684 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gkehub-configmanagement package uses inline types. diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/services/__init__.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/services/__init__.py new file mode 100644 index 0000000..89a37dc --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/__init__.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/__init__.py new file mode 100644 index 0000000..c4cee09 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/__init__.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .configmanagement import ( + ConfigSync, + ConfigSyncDeploymentState, + ConfigSyncState, + ConfigSyncVersion, + ErrorResource, + GatekeeperDeploymentState, + GitConfig, + GroupVersionKind, + HierarchyControllerConfig, + HierarchyControllerDeploymentState, + HierarchyControllerState, + HierarchyControllerVersion, + InstallError, + MembershipSpec, + MembershipState, + OperatorState, + PolicyController, + PolicyControllerState, + PolicyControllerVersion, + SyncError, + SyncState, + DeploymentState, +) + +__all__ = ( + 'ConfigSync', + 'ConfigSyncDeploymentState', + 'ConfigSyncState', + 'ConfigSyncVersion', + 'ErrorResource', + 'GatekeeperDeploymentState', + 'GitConfig', + 'GroupVersionKind', + 'HierarchyControllerConfig', + 'HierarchyControllerDeploymentState', + 'HierarchyControllerState', + 'HierarchyControllerVersion', + 'InstallError', + 'MembershipSpec', + 'MembershipState', + 'OperatorState', + 'PolicyController', + 'PolicyControllerState', + 'PolicyControllerVersion', + 'SyncError', + 'SyncState', + 'DeploymentState', +) diff --git a/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/configmanagement.py b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/configmanagement.py new file mode 100644 index 0000000..06498be --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/google/cloud/gkehub/configmanagement_v1/types/configmanagement.py @@ -0,0 +1,833 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.configmanagement.v1', + manifest={ + 'DeploymentState', + 'MembershipState', + 'MembershipSpec', + 'ConfigSync', + 'GitConfig', + 'PolicyController', + 'HierarchyControllerConfig', + 'HierarchyControllerDeploymentState', + 'HierarchyControllerVersion', + 'HierarchyControllerState', + 'OperatorState', + 'InstallError', + 'ConfigSyncState', + 'ConfigSyncVersion', + 'ConfigSyncDeploymentState', + 'SyncState', + 'SyncError', + 'ErrorResource', + 'GroupVersionKind', + 'PolicyControllerState', + 'PolicyControllerVersion', + 'GatekeeperDeploymentState', + }, +) + + +class DeploymentState(proto.Enum): + r"""Enum representing the state of an ACM's deployment on a + cluster + + Values: + DEPLOYMENT_STATE_UNSPECIFIED (0): + Deployment's state cannot be determined + NOT_INSTALLED (1): + Deployment is not installed + INSTALLED (2): + Deployment is installed + ERROR (3): + Deployment was attempted to be installed, but + has errors + """ + DEPLOYMENT_STATE_UNSPECIFIED = 0 + NOT_INSTALLED = 1 + INSTALLED = 2 + ERROR = 3 + + +class MembershipState(proto.Message): + r"""**Anthos Config Management**: State for a single cluster. + + Attributes: + cluster_name (str): + The user-defined name for the cluster used by + ClusterSelectors to group clusters together. This should + match Membership's membership_name, unless the user + installed ACM on the cluster manually prior to enabling the + ACM hub feature. Unique within a Anthos Config Management + installation. + membership_spec (google.cloud.gkehub.configmanagement_v1.types.MembershipSpec): + Membership configuration in the cluster. This + represents the actual state in the cluster, + while the MembershipSpec in the FeatureSpec + represents the intended state + operator_state (google.cloud.gkehub.configmanagement_v1.types.OperatorState): + Current install status of ACM's Operator + config_sync_state (google.cloud.gkehub.configmanagement_v1.types.ConfigSyncState): + Current sync status + policy_controller_state (google.cloud.gkehub.configmanagement_v1.types.PolicyControllerState): + PolicyController status + hierarchy_controller_state (google.cloud.gkehub.configmanagement_v1.types.HierarchyControllerState): + Hierarchy Controller status + """ + + cluster_name: str = proto.Field( + proto.STRING, + number=1, + ) + membership_spec: 'MembershipSpec' = proto.Field( + proto.MESSAGE, + number=2, + message='MembershipSpec', + ) + operator_state: 'OperatorState' = proto.Field( + proto.MESSAGE, + number=3, + message='OperatorState', + ) + config_sync_state: 'ConfigSyncState' = proto.Field( + proto.MESSAGE, + number=4, + message='ConfigSyncState', + ) + policy_controller_state: 'PolicyControllerState' = proto.Field( + proto.MESSAGE, + number=5, + message='PolicyControllerState', + ) + hierarchy_controller_state: 'HierarchyControllerState' = proto.Field( + proto.MESSAGE, + number=7, + message='HierarchyControllerState', + ) + + +class MembershipSpec(proto.Message): + r"""**Anthos Config Management**: Configuration for a single cluster. + Intended to parallel the ConfigManagement CR. + + Attributes: + config_sync (google.cloud.gkehub.configmanagement_v1.types.ConfigSync): + Config Sync configuration for the cluster. + policy_controller (google.cloud.gkehub.configmanagement_v1.types.PolicyController): + Policy Controller configuration for the + cluster. + hierarchy_controller (google.cloud.gkehub.configmanagement_v1.types.HierarchyControllerConfig): + Hierarchy Controller configuration for the + cluster. + version (str): + Version of ACM installed. + """ + + config_sync: 'ConfigSync' = proto.Field( + proto.MESSAGE, + number=1, + message='ConfigSync', + ) + policy_controller: 'PolicyController' = proto.Field( + proto.MESSAGE, + number=2, + message='PolicyController', + ) + hierarchy_controller: 'HierarchyControllerConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='HierarchyControllerConfig', + ) + version: str = proto.Field( + proto.STRING, + number=10, + ) + + +class ConfigSync(proto.Message): + r"""Configuration for Config Sync + + Attributes: + git (google.cloud.gkehub.configmanagement_v1.types.GitConfig): + Git repo configuration for the cluster. + source_format (str): + Specifies whether the Config Sync Repo is + in “hierarchical” or “unstructured” mode. + """ + + git: 'GitConfig' = proto.Field( + proto.MESSAGE, + number=7, + message='GitConfig', + ) + source_format: str = proto.Field( + proto.STRING, + number=8, + ) + + +class GitConfig(proto.Message): + r"""Git repo configuration for a single cluster. + + Attributes: + sync_repo (str): + The URL of the Git repository to use as the + source of truth. + sync_branch (str): + The branch of the repository to sync from. + Default: master. + policy_dir (str): + The path within the Git repository that + represents the top level of the repo to sync. + Default: the root directory of the repository. + sync_wait_secs (int): + Period in seconds between consecutive syncs. + Default: 15. + sync_rev (str): + Git revision (tag or hash) to check out. + Default HEAD. + secret_type (str): + Type of secret configured for access to the + Git repo. + https_proxy (str): + URL for the HTTPS proxy to be used when + communicating with the Git repo. + gcp_service_account_email (str): + The GCP Service Account Email used for auth when secret_type + is gcpServiceAccount. + """ + + sync_repo: str = proto.Field( + proto.STRING, + number=1, + ) + sync_branch: str = proto.Field( + proto.STRING, + number=2, + ) + policy_dir: str = proto.Field( + proto.STRING, + number=3, + ) + sync_wait_secs: int = proto.Field( + proto.INT64, + number=4, + ) + sync_rev: str = proto.Field( + proto.STRING, + number=5, + ) + secret_type: str = proto.Field( + proto.STRING, + number=6, + ) + https_proxy: str = proto.Field( + proto.STRING, + number=7, + ) + gcp_service_account_email: str = proto.Field( + proto.STRING, + number=8, + ) + + +class PolicyController(proto.Message): + r"""Configuration for Policy Controller + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enabled (bool): + Enables the installation of Policy + Controller. If false, the rest of + PolicyController fields take no effect. + template_library_installed (bool): + Installs the default template library along + with Policy Controller. + + This field is a member of `oneof`_ ``_template_library_installed``. + audit_interval_seconds (int): + Sets the interval for Policy Controller Audit + Scans (in seconds). When set to 0, this disables + audit functionality altogether. + + This field is a member of `oneof`_ ``_audit_interval_seconds``. + exemptable_namespaces (MutableSequence[str]): + The set of namespaces that are excluded from + Policy Controller checks. Namespaces do not need + to currently exist on the cluster. + referential_rules_enabled (bool): + Enables the ability to use Constraint + Templates that reference to objects other than + the object currently being evaluated. + log_denies_enabled (bool): + Logs all denies and dry run failures. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + template_library_installed: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + audit_interval_seconds: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + exemptable_namespaces: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + referential_rules_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + log_denies_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class HierarchyControllerConfig(proto.Message): + r"""Configuration for Hierarchy Controller + + Attributes: + enabled (bool): + Whether Hierarchy Controller is enabled in + this cluster. + enable_pod_tree_labels (bool): + Whether pod tree labels are enabled in this + cluster. + enable_hierarchical_resource_quota (bool): + Whether hierarchical resource quota is + enabled in this cluster. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_pod_tree_labels: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_hierarchical_resource_quota: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class HierarchyControllerDeploymentState(proto.Message): + r"""Deployment state for Hierarchy Controller + + Attributes: + hnc (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + The deployment state for open source HNC + (e.g. v0.7.0-hc.0) + extension (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + The deployment state for Hierarchy Controller + extension (e.g. v0.7.0-hc.1) + """ + + hnc: 'DeploymentState' = proto.Field( + proto.ENUM, + number=1, + enum='DeploymentState', + ) + extension: 'DeploymentState' = proto.Field( + proto.ENUM, + number=2, + enum='DeploymentState', + ) + + +class HierarchyControllerVersion(proto.Message): + r"""Version for Hierarchy Controller + + Attributes: + hnc (str): + Version for open source HNC + extension (str): + Version for Hierarchy Controller extension + """ + + hnc: str = proto.Field( + proto.STRING, + number=1, + ) + extension: str = proto.Field( + proto.STRING, + number=2, + ) + + +class HierarchyControllerState(proto.Message): + r"""State for Hierarchy Controller + + Attributes: + version (google.cloud.gkehub.configmanagement_v1.types.HierarchyControllerVersion): + The version for Hierarchy Controller + state (google.cloud.gkehub.configmanagement_v1.types.HierarchyControllerDeploymentState): + The deployment state for Hierarchy Controller + """ + + version: 'HierarchyControllerVersion' = proto.Field( + proto.MESSAGE, + number=1, + message='HierarchyControllerVersion', + ) + state: 'HierarchyControllerDeploymentState' = proto.Field( + proto.MESSAGE, + number=2, + message='HierarchyControllerDeploymentState', + ) + + +class OperatorState(proto.Message): + r"""State information for an ACM's Operator + + Attributes: + version (str): + The semenatic version number of the operator + deployment_state (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + The state of the Operator's deployment + errors (MutableSequence[google.cloud.gkehub.configmanagement_v1.types.InstallError]): + Install errors. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + deployment_state: 'DeploymentState' = proto.Field( + proto.ENUM, + number=2, + enum='DeploymentState', + ) + errors: MutableSequence['InstallError'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='InstallError', + ) + + +class InstallError(proto.Message): + r"""Errors pertaining to the installation of ACM + + Attributes: + error_message (str): + A string representing the user facing error + message + """ + + error_message: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ConfigSyncState(proto.Message): + r"""State information for ConfigSync + + Attributes: + version (google.cloud.gkehub.configmanagement_v1.types.ConfigSyncVersion): + The version of ConfigSync deployed + deployment_state (google.cloud.gkehub.configmanagement_v1.types.ConfigSyncDeploymentState): + Information about the deployment of + ConfigSync, including the version of the various + Pods deployed + sync_state (google.cloud.gkehub.configmanagement_v1.types.SyncState): + The state of ConfigSync's process to sync + configs to a cluster + """ + + version: 'ConfigSyncVersion' = proto.Field( + proto.MESSAGE, + number=1, + message='ConfigSyncVersion', + ) + deployment_state: 'ConfigSyncDeploymentState' = proto.Field( + proto.MESSAGE, + number=2, + message='ConfigSyncDeploymentState', + ) + sync_state: 'SyncState' = proto.Field( + proto.MESSAGE, + number=3, + message='SyncState', + ) + + +class ConfigSyncVersion(proto.Message): + r"""Specific versioning information pertaining to ConfigSync's + Pods + + Attributes: + importer (str): + Version of the deployed importer pod + syncer (str): + Version of the deployed syncer pod + git_sync (str): + Version of the deployed git-sync pod + monitor (str): + Version of the deployed monitor pod + reconciler_manager (str): + Version of the deployed reconciler-manager + pod + root_reconciler (str): + Version of the deployed reconciler container + in root-reconciler pod + """ + + importer: str = proto.Field( + proto.STRING, + number=1, + ) + syncer: str = proto.Field( + proto.STRING, + number=2, + ) + git_sync: str = proto.Field( + proto.STRING, + number=3, + ) + monitor: str = proto.Field( + proto.STRING, + number=4, + ) + reconciler_manager: str = proto.Field( + proto.STRING, + number=5, + ) + root_reconciler: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ConfigSyncDeploymentState(proto.Message): + r"""The state of ConfigSync's deployment on a cluster + + Attributes: + importer (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of the importer pod + syncer (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of the syncer pod + git_sync (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of the git-sync pod + monitor (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of the monitor pod + reconciler_manager (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of reconciler-manager pod + root_reconciler (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Deployment state of root-reconciler + """ + + importer: 'DeploymentState' = proto.Field( + proto.ENUM, + number=1, + enum='DeploymentState', + ) + syncer: 'DeploymentState' = proto.Field( + proto.ENUM, + number=2, + enum='DeploymentState', + ) + git_sync: 'DeploymentState' = proto.Field( + proto.ENUM, + number=3, + enum='DeploymentState', + ) + monitor: 'DeploymentState' = proto.Field( + proto.ENUM, + number=4, + enum='DeploymentState', + ) + reconciler_manager: 'DeploymentState' = proto.Field( + proto.ENUM, + number=5, + enum='DeploymentState', + ) + root_reconciler: 'DeploymentState' = proto.Field( + proto.ENUM, + number=6, + enum='DeploymentState', + ) + + +class SyncState(proto.Message): + r"""State indicating an ACM's progress syncing configurations to + a cluster + + Attributes: + source_token (str): + Token indicating the state of the repo. + import_token (str): + Token indicating the state of the importer. + sync_token (str): + Token indicating the state of the syncer. + last_sync (str): + Deprecated: use last_sync_time instead. Timestamp of when + ACM last successfully synced the repo The time format is + specified in https://golang.org/pkg/time/#Time.String + last_sync_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp type of when ACM last successfully + synced the repo + code (google.cloud.gkehub.configmanagement_v1.types.SyncState.SyncCode): + Sync status code + errors (MutableSequence[google.cloud.gkehub.configmanagement_v1.types.SyncError]): + A list of errors resulting from problematic + configs. This list will be truncated after 100 + errors, although it is unlikely for that many + errors to simultaneously exist. + """ + class SyncCode(proto.Enum): + r"""An enum representing an ACM's status syncing configs to a + cluster + + Values: + SYNC_CODE_UNSPECIFIED (0): + ACM cannot determine a sync code + SYNCED (1): + ACM successfully synced the git Repo with the + cluster + PENDING (2): + ACM is in the progress of syncing a new + change + ERROR (3): + Indicates an error configuring ACM, and user + action is required + NOT_CONFIGURED (4): + ACM has been installed (operator manifest + deployed), but not configured. + NOT_INSTALLED (5): + ACM has not been installed (no operator pod + found) + UNAUTHORIZED (6): + Error authorizing with the cluster + UNREACHABLE (7): + Cluster could not be reached + """ + SYNC_CODE_UNSPECIFIED = 0 + SYNCED = 1 + PENDING = 2 + ERROR = 3 + NOT_CONFIGURED = 4 + NOT_INSTALLED = 5 + UNAUTHORIZED = 6 + UNREACHABLE = 7 + + source_token: str = proto.Field( + proto.STRING, + number=1, + ) + import_token: str = proto.Field( + proto.STRING, + number=2, + ) + sync_token: str = proto.Field( + proto.STRING, + number=3, + ) + last_sync: str = proto.Field( + proto.STRING, + number=4, + ) + last_sync_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + code: SyncCode = proto.Field( + proto.ENUM, + number=5, + enum=SyncCode, + ) + errors: MutableSequence['SyncError'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='SyncError', + ) + + +class SyncError(proto.Message): + r"""An ACM created error representing a problem syncing + configurations + + Attributes: + code (str): + An ACM defined error code + error_message (str): + A description of the error + error_resources (MutableSequence[google.cloud.gkehub.configmanagement_v1.types.ErrorResource]): + A list of config(s) associated with the + error, if any + """ + + code: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + error_resources: MutableSequence['ErrorResource'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ErrorResource', + ) + + +class ErrorResource(proto.Message): + r"""Model for a config file in the git repo with an associated + Sync error + + Attributes: + source_path (str): + Path in the git repo of the erroneous config + resource_name (str): + Metadata name of the resource that is causing + an error + resource_namespace (str): + Namespace of the resource that is causing an + error + resource_gvk (google.cloud.gkehub.configmanagement_v1.types.GroupVersionKind): + Group/version/kind of the resource that is + causing an error + """ + + source_path: str = proto.Field( + proto.STRING, + number=1, + ) + resource_name: str = proto.Field( + proto.STRING, + number=2, + ) + resource_namespace: str = proto.Field( + proto.STRING, + number=3, + ) + resource_gvk: 'GroupVersionKind' = proto.Field( + proto.MESSAGE, + number=4, + message='GroupVersionKind', + ) + + +class GroupVersionKind(proto.Message): + r"""A Kubernetes object's GVK + + Attributes: + group (str): + Kubernetes Group + version (str): + Kubernetes Version + kind (str): + Kubernetes Kind + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + kind: str = proto.Field( + proto.STRING, + number=3, + ) + + +class PolicyControllerState(proto.Message): + r"""State for PolicyControllerState. + + Attributes: + version (google.cloud.gkehub.configmanagement_v1.types.PolicyControllerVersion): + The version of Gatekeeper Policy Controller + deployed. + deployment_state (google.cloud.gkehub.configmanagement_v1.types.GatekeeperDeploymentState): + The state about the policy controller + installation. + """ + + version: 'PolicyControllerVersion' = proto.Field( + proto.MESSAGE, + number=1, + message='PolicyControllerVersion', + ) + deployment_state: 'GatekeeperDeploymentState' = proto.Field( + proto.MESSAGE, + number=2, + message='GatekeeperDeploymentState', + ) + + +class PolicyControllerVersion(proto.Message): + r"""The build version of Gatekeeper Policy Controller is using. + + Attributes: + version (str): + The gatekeeper image tag that is composed of + ACM version, git tag, build number. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GatekeeperDeploymentState(proto.Message): + r"""State of Policy Controller installation. + + Attributes: + gatekeeper_controller_manager_state (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Status of gatekeeper-controller-manager pod. + gatekeeper_audit (google.cloud.gkehub.configmanagement_v1.types.DeploymentState): + Status of gatekeeper-audit deployment. + """ + + gatekeeper_controller_manager_state: 'DeploymentState' = proto.Field( + proto.ENUM, + number=1, + enum='DeploymentState', + ) + gatekeeper_audit: 'DeploymentState' = proto.Field( + proto.ENUM, + number=2, + enum='DeploymentState', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/configmanagement/mypy.ini b/owl-bot-staging/v1/configmanagement/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/configmanagement/noxfile.py b/owl-bot-staging/v1/configmanagement/noxfile.py new file mode 100644 index 0000000..4fba476 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gkehub/configmanagement_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@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( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/configmanagement/scripts/fixup_configmanagement_v1_keywords.py b/owl-bot-staging/v1/configmanagement/scripts/fixup_configmanagement_v1_keywords.py new file mode 100644 index 0000000..89ca15d --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/scripts/fixup_configmanagement_v1_keywords.py @@ -0,0 +1,175 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 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 configmanagementCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + } + + 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=configmanagementCallTransformer(), +): + """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 configmanagement 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/v1/configmanagement/setup.py b/owl-bot-staging/v1/configmanagement/setup.py new file mode 100644 index 0000000..8eccced --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-gkehub-configmanagement' + + +description = "Google Cloud Gkehub Configmanagement API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/gkehub/configmanagement/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +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.0, <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.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-gkehub-configmanagement" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.gkehub"] + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.10.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.11.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.12.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.12.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.7.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.7.txt new file mode 100644 index 0000000..6c44adf --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# 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.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.8.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/configmanagement/testing/constraints-3.9.txt b/owl-bot-staging/v1/configmanagement/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/configmanagement/tests/__init__.py b/owl-bot-staging/v1/configmanagement/tests/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/tests/unit/__init__.py b/owl-bot-staging/v1/configmanagement/tests/unit/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/configmanagement/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/configmanagement/tests/unit/gapic/configmanagement_v1/__init__.py b/owl-bot-staging/v1/configmanagement/tests/unit/gapic/configmanagement_v1/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/configmanagement/tests/unit/gapic/configmanagement_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/docs/_static/custom.css b/owl-bot-staging/v1/docs/_static/custom.css new file mode 100644 index 0000000..06423be --- /dev/null +++ b/owl-bot-staging/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..121febc --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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-gke-hub 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-gke-hub" +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-gke-hub-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-gke-hub.tex", + u"google-cloud-gke-hub 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-gke-hub", + u"Google Cloud Gkehub 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-gke-hub", + u"google-cloud-gke-hub Documentation", + author, + "google-cloud-gke-hub", + "GAPIC library for Google Cloud Gkehub 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/v1/docs/gkehub_v1/gke_hub.rst b/owl-bot-staging/v1/docs/gkehub_v1/gke_hub.rst new file mode 100644 index 0000000..198ae72 --- /dev/null +++ b/owl-bot-staging/v1/docs/gkehub_v1/gke_hub.rst @@ -0,0 +1,10 @@ +GkeHub +------------------------ + +.. automodule:: google.cloud.gkehub_v1.services.gke_hub + :members: + :inherited-members: + +.. automodule:: google.cloud.gkehub_v1.services.gke_hub.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/gkehub_v1/services_.rst b/owl-bot-staging/v1/docs/gkehub_v1/services_.rst new file mode 100644 index 0000000..ff81f05 --- /dev/null +++ b/owl-bot-staging/v1/docs/gkehub_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Gkehub v1 API +======================================= +.. toctree:: + :maxdepth: 2 + + gke_hub diff --git a/owl-bot-staging/v1/docs/gkehub_v1/types_.rst b/owl-bot-staging/v1/docs/gkehub_v1/types_.rst new file mode 100644 index 0000000..e04d63d --- /dev/null +++ b/owl-bot-staging/v1/docs/gkehub_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gkehub v1 API +==================================== + +.. automodule:: google.cloud.gkehub_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..64470ac --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + gkehub_v1/services + gkehub_v1/types diff --git a/owl-bot-staging/v1/google/cloud/gkehub/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub/__init__.py new file mode 100644 index 0000000..969e163 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub/__init__.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.gkehub_v1.services.gke_hub.client import GkeHubClient +from google.cloud.gkehub_v1.services.gke_hub.async_client import GkeHubAsyncClient + +from google.cloud.gkehub_v1.types.feature import CommonFeatureSpec +from google.cloud.gkehub_v1.types.feature import CommonFeatureState +from google.cloud.gkehub_v1.types.feature import Feature +from google.cloud.gkehub_v1.types.feature import FeatureResourceState +from google.cloud.gkehub_v1.types.feature import FeatureState +from google.cloud.gkehub_v1.types.feature import MembershipFeatureSpec +from google.cloud.gkehub_v1.types.feature import MembershipFeatureState +from google.cloud.gkehub_v1.types.membership import Authority +from google.cloud.gkehub_v1.types.membership import GkeCluster +from google.cloud.gkehub_v1.types.membership import KubernetesMetadata +from google.cloud.gkehub_v1.types.membership import KubernetesResource +from google.cloud.gkehub_v1.types.membership import Membership +from google.cloud.gkehub_v1.types.membership import MembershipEndpoint +from google.cloud.gkehub_v1.types.membership import MembershipState +from google.cloud.gkehub_v1.types.membership import MonitoringConfig +from google.cloud.gkehub_v1.types.membership import ResourceManifest +from google.cloud.gkehub_v1.types.membership import ResourceOptions +from google.cloud.gkehub_v1.types.service import ConnectAgentResource +from google.cloud.gkehub_v1.types.service import CreateFeatureRequest +from google.cloud.gkehub_v1.types.service import CreateMembershipRequest +from google.cloud.gkehub_v1.types.service import DeleteFeatureRequest +from google.cloud.gkehub_v1.types.service import DeleteMembershipRequest +from google.cloud.gkehub_v1.types.service import GenerateConnectManifestRequest +from google.cloud.gkehub_v1.types.service import GenerateConnectManifestResponse +from google.cloud.gkehub_v1.types.service import GetFeatureRequest +from google.cloud.gkehub_v1.types.service import GetMembershipRequest +from google.cloud.gkehub_v1.types.service import ListFeaturesRequest +from google.cloud.gkehub_v1.types.service import ListFeaturesResponse +from google.cloud.gkehub_v1.types.service import ListMembershipsRequest +from google.cloud.gkehub_v1.types.service import ListMembershipsResponse +from google.cloud.gkehub_v1.types.service import OperationMetadata +from google.cloud.gkehub_v1.types.service import TypeMeta +from google.cloud.gkehub_v1.types.service import UpdateFeatureRequest +from google.cloud.gkehub_v1.types.service import UpdateMembershipRequest + +__all__ = ('GkeHubClient', + 'GkeHubAsyncClient', + 'CommonFeatureSpec', + 'CommonFeatureState', + 'Feature', + 'FeatureResourceState', + 'FeatureState', + 'MembershipFeatureSpec', + 'MembershipFeatureState', + 'Authority', + 'GkeCluster', + 'KubernetesMetadata', + 'KubernetesResource', + 'Membership', + 'MembershipEndpoint', + 'MembershipState', + 'MonitoringConfig', + 'ResourceManifest', + 'ResourceOptions', + 'ConnectAgentResource', + 'CreateFeatureRequest', + 'CreateMembershipRequest', + 'DeleteFeatureRequest', + 'DeleteMembershipRequest', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'GetFeatureRequest', + 'GetMembershipRequest', + 'ListFeaturesRequest', + 'ListFeaturesResponse', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'OperationMetadata', + 'TypeMeta', + 'UpdateFeatureRequest', + 'UpdateMembershipRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub/gapic_version.py b/owl-bot-staging/v1/google/cloud/gkehub/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/google/cloud/gkehub/py.typed b/owl-bot-staging/v1/google/cloud/gkehub/py.typed new file mode 100644 index 0000000..7a6a6d0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-hub package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/__init__.py new file mode 100644 index 0000000..b112d69 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/__init__.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.gke_hub import GkeHubClient +from .services.gke_hub import GkeHubAsyncClient + +from .types.feature import CommonFeatureSpec +from .types.feature import CommonFeatureState +from .types.feature import Feature +from .types.feature import FeatureResourceState +from .types.feature import FeatureState +from .types.feature import MembershipFeatureSpec +from .types.feature import MembershipFeatureState +from .types.membership import Authority +from .types.membership import GkeCluster +from .types.membership import KubernetesMetadata +from .types.membership import KubernetesResource +from .types.membership import Membership +from .types.membership import MembershipEndpoint +from .types.membership import MembershipState +from .types.membership import MonitoringConfig +from .types.membership import ResourceManifest +from .types.membership import ResourceOptions +from .types.service import ConnectAgentResource +from .types.service import CreateFeatureRequest +from .types.service import CreateMembershipRequest +from .types.service import DeleteFeatureRequest +from .types.service import DeleteMembershipRequest +from .types.service import GenerateConnectManifestRequest +from .types.service import GenerateConnectManifestResponse +from .types.service import GetFeatureRequest +from .types.service import GetMembershipRequest +from .types.service import ListFeaturesRequest +from .types.service import ListFeaturesResponse +from .types.service import ListMembershipsRequest +from .types.service import ListMembershipsResponse +from .types.service import OperationMetadata +from .types.service import TypeMeta +from .types.service import UpdateFeatureRequest +from .types.service import UpdateMembershipRequest + +__all__ = ( + 'GkeHubAsyncClient', +'Authority', +'CommonFeatureSpec', +'CommonFeatureState', +'ConnectAgentResource', +'CreateFeatureRequest', +'CreateMembershipRequest', +'DeleteFeatureRequest', +'DeleteMembershipRequest', +'Feature', +'FeatureResourceState', +'FeatureState', +'GenerateConnectManifestRequest', +'GenerateConnectManifestResponse', +'GetFeatureRequest', +'GetMembershipRequest', +'GkeCluster', +'GkeHubClient', +'KubernetesMetadata', +'KubernetesResource', +'ListFeaturesRequest', +'ListFeaturesResponse', +'ListMembershipsRequest', +'ListMembershipsResponse', +'Membership', +'MembershipEndpoint', +'MembershipFeatureSpec', +'MembershipFeatureState', +'MembershipState', +'MonitoringConfig', +'OperationMetadata', +'ResourceManifest', +'ResourceOptions', +'TypeMeta', +'UpdateFeatureRequest', +'UpdateMembershipRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_metadata.json new file mode 100644 index 0000000..042eb2e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_metadata.json @@ -0,0 +1,193 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gkehub_v1", + "protoPackage": "google.cloud.gkehub.v1", + "schema": "1.0", + "services": { + "GkeHub": { + "clients": { + "grpc": { + "libraryClient": "GkeHubClient", + "rpcs": { + "CreateFeature": { + "methods": [ + "create_feature" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteFeature": { + "methods": [ + "delete_feature" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GetFeature": { + "methods": [ + "get_feature" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListFeatures": { + "methods": [ + "list_features" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateFeature": { + "methods": [ + "update_feature" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GkeHubAsyncClient", + "rpcs": { + "CreateFeature": { + "methods": [ + "create_feature" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteFeature": { + "methods": [ + "delete_feature" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GetFeature": { + "methods": [ + "get_feature" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListFeatures": { + "methods": [ + "list_features" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateFeature": { + "methods": [ + "update_feature" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + } + } + }, + "rest": { + "libraryClient": "GkeHubClient", + "rpcs": { + "CreateFeature": { + "methods": [ + "create_feature" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteFeature": { + "methods": [ + "delete_feature" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GetFeature": { + "methods": [ + "get_feature" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListFeatures": { + "methods": [ + "list_features" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateFeature": { + "methods": [ + "update_feature" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/google/cloud/gkehub_v1/py.typed b/owl-bot-staging/v1/google/cloud/gkehub_v1/py.typed new file mode 100644 index 0000000..7a6a6d0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-hub package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/__init__.py new file mode 100644 index 0000000..89a37dc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/google/cloud/gkehub_v1/services/gke_hub/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/__init__.py new file mode 100644 index 0000000..7eb7c6e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GkeHubClient +from .async_client import GkeHubAsyncClient + +__all__ = ( + 'GkeHubClient', + 'GkeHubAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/async_client.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/async_client.py new file mode 100644 index 0000000..b0f7980 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/async_client.py @@ -0,0 +1,1542 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.gkehub_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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gkehub_v1.services.gke_hub import pagers +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +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 GkeHubTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GkeHubGrpcAsyncIOTransport +from .client import GkeHubClient + + +class GkeHubAsyncClient: + """The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + """ + + _client: GkeHubClient + + DEFAULT_ENDPOINT = GkeHubClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GkeHubClient.DEFAULT_MTLS_ENDPOINT + + feature_path = staticmethod(GkeHubClient.feature_path) + parse_feature_path = staticmethod(GkeHubClient.parse_feature_path) + membership_path = staticmethod(GkeHubClient.membership_path) + parse_membership_path = staticmethod(GkeHubClient.parse_membership_path) + common_billing_account_path = staticmethod(GkeHubClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GkeHubClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GkeHubClient.common_folder_path) + parse_common_folder_path = staticmethod(GkeHubClient.parse_common_folder_path) + common_organization_path = staticmethod(GkeHubClient.common_organization_path) + parse_common_organization_path = staticmethod(GkeHubClient.parse_common_organization_path) + common_project_path = staticmethod(GkeHubClient.common_project_path) + parse_common_project_path = staticmethod(GkeHubClient.parse_common_project_path) + common_location_path = staticmethod(GkeHubClient.common_location_path) + parse_common_location_path = staticmethod(GkeHubClient.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: + GkeHubAsyncClient: The constructed client. + """ + return GkeHubClient.from_service_account_info.__func__(GkeHubAsyncClient, 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: + GkeHubAsyncClient: The constructed client. + """ + return GkeHubClient.from_service_account_file.__func__(GkeHubAsyncClient, 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 GkeHubClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GkeHubTransport: + """Returns the transport used by the client instance. + + Returns: + GkeHubTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(GkeHubClient).get_transport_class, type(GkeHubClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, GkeHubTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gke hub client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.GkeHubTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = GkeHubClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_memberships(self, + request: Optional[Union[service.ListMembershipsRequest, 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.ListMembershipsAsyncPager: + r"""Lists Memberships in a given project and location. + + .. 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 gkehub_v1 + + async def sample_list_memberships(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListMembershipsRequest, dict]]): + The request object. Request message for ``GkeHub.ListMemberships`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` + list memberships in all the regions. + + 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.gkehub_v1.services.gke_hub.pagers.ListMembershipsAsyncPager: + Response message for the GkeHub.ListMemberships method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.ListMembershipsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_memberships, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembershipsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_features(self, + request: Optional[Union[service.ListFeaturesRequest, 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.ListFeaturesAsyncPager: + r"""Lists Features in a given project and location. + + .. 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 gkehub_v1 + + async def sample_list_features(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFeaturesRequest( + ) + + # Make the request + page_result = client.list_features(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListFeaturesRequest, dict]]): + The request object. Request message for ``GkeHub.ListFeatures`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Features will 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.gkehub_v1.services.gke_hub.pagers.ListFeaturesAsyncPager: + Response message for the GkeHub.ListFeatures method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.ListFeaturesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_features, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFeaturesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership(self, + request: Optional[Union[service.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Gets the details of a Membership. + + .. 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 gkehub_v1 + + async def sample_get_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetMembershipRequest, dict]]): + The request object. Request message for ``GkeHub.GetMembership`` method. + name (:class:`str`): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.gkehub_v1.types.Membership: + Membership contains information about + a member cluster. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.GetMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_feature(self, + request: Optional[Union[service.GetFeatureRequest, 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]] = (), + ) -> feature.Feature: + r"""Gets details of a single Feature. + + .. 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 gkehub_v1 + + async def sample_get_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFeatureRequest( + ) + + # Make the request + response = await client.get_feature(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetFeatureRequest, dict]]): + The request object. Request message for ``GkeHub.GetFeature`` method. + name (:class:`str`): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*`` + + 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.gkehub_v1.types.Feature: + Feature represents the settings and + status of any Hub Feature. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.GetFeatureRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_feature, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_membership(self, + request: Optional[Union[service.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[membership.Membership] = None, + membership_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 Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + .. 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 gkehub_v1 + + async def sample_create_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateMembershipRequest, dict]]): + The request object. Request message for the ``GkeHub.CreateMembership`` + method. + parent (:class:`str`): + Required. The parent (project and location) where the + Memberships will 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. + resource (:class:`google.cloud.gkehub_v1.types.Membership`): + Required. The membership to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_id (:class:`str`): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``membership_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, membership_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if membership_id is not None: + request.membership_id = membership_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + membership.Membership, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_feature(self, + request: Optional[Union[service.CreateFeatureRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[feature.Feature] = None, + feature_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"""Adds a new Feature. + + .. 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 gkehub_v1 + + async def sample_create_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFeatureRequest( + ) + + # Make the request + operation = client.create_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateFeatureRequest, dict]]): + The request object. Request message for the ``GkeHub.CreateFeature`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Feature will 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. + resource (:class:`google.cloud.gkehub_v1.types.Feature`): + The Feature resource to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature_id (:class:`str`): + The ID of the feature to create. + This corresponds to the ``feature_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Feature` Feature + represents the settings and status of any Hub Feature. + + """ + # 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, resource, feature_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateFeatureRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if feature_id is not None: + request.feature_id = feature_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_feature, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + feature.Feature, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_membership(self, + request: Optional[Union[service.DeleteMembershipRequest, 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"""Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + .. 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 gkehub_v1 + + async def sample_delete_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteMembershipRequest, dict]]): + The request object. Request message for ``GkeHub.DeleteMembership`` method. + name (:class:`str`): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DeleteMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_feature(self, + request: Optional[Union[service.DeleteFeatureRequest, 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"""Removes a Feature. + + .. 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 gkehub_v1 + + async def sample_delete_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFeatureRequest( + ) + + # Make the request + operation = client.delete_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteFeatureRequest, dict]]): + The request object. Request message for ``GkeHub.DeleteFeature`` method. + name (:class:`str`): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DeleteFeatureRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_feature, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_membership(self, + request: Optional[Union[service.UpdateMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[membership.Membership] = 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 an existing Membership. + + .. 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 gkehub_v1 + + async def sample_update_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateMembershipRequest, dict]]): + The request object. Request message for ``GkeHub.UpdateMembership`` method. + name (:class:`str`): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.gkehub_v1.types.Membership`): + Required. Only fields specified in update_mask are + updated. If you specify a field in the update_mask but + don't specify its value here that field will be deleted. + If you are updating a map field, set the value of a key + to null or empty string to delete the key from the map. + It's not possible to update a key's value to the empty + string. If you specify the update_mask to be a special + path "*", fully replaces all user-modifiable fields to + match ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.UpdateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + membership.Membership, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_feature(self, + request: Optional[Union[service.UpdateFeatureRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[feature.Feature] = 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 an existing Feature. + + .. 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 gkehub_v1 + + async def sample_update_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFeatureRequest( + ) + + # Make the request + operation = client.update_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateFeatureRequest, dict]]): + The request object. Request message for ``GkeHub.UpdateFeature`` method. + name (:class:`str`): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.gkehub_v1.types.Feature`): + Only fields specified in update_mask are updated. If you + specify a field in the update_mask but don't specify its + value here that field will be deleted. If you are + updating a map field, set the value of a key to null or + empty string to delete the key from the map. It's not + possible to update a key's value to the empty string. If + you specify the update_mask to be a special path "*", + fully replaces all user-modifiable fields to match + ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Mask of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Feature` Feature + represents the settings and status of any Hub Feature. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.UpdateFeatureRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_feature, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + feature.Feature, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_connect_manifest(self, + request: Optional[Union[service.GenerateConnectManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateConnectManifestResponse: + r"""Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + .. 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 gkehub_v1 + + async def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GenerateConnectManifestRequest, dict]]): + The request object. Request message for ``GkeHub.GenerateConnectManifest`` + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1.types.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + # Create or coerce a protobuf request object. + request = service.GenerateConnectManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_connect_manifest, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "GkeHubAsyncClient": + 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__ = ( + "GkeHubAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/client.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/client.py new file mode 100644 index 0000000..9d38f2f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/client.py @@ -0,0 +1,1756 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.gkehub_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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gkehub_v1.services.gke_hub import pagers +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +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 GkeHubTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GkeHubGrpcTransport +from .transports.grpc_asyncio import GkeHubGrpcAsyncIOTransport +from .transports.rest import GkeHubRestTransport + + +class GkeHubClientMeta(type): + """Metaclass for the GkeHub 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[GkeHubTransport]] + _transport_registry["grpc"] = GkeHubGrpcTransport + _transport_registry["grpc_asyncio"] = GkeHubGrpcAsyncIOTransport + _transport_registry["rest"] = GkeHubRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[GkeHubTransport]: + """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 GkeHubClient(metaclass=GkeHubClientMeta): + """The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gkehub.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GkeHubClient: 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: + GkeHubClient: 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) -> GkeHubTransport: + """Returns the transport used by the client instance. + + Returns: + GkeHubTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def feature_path(project: str,location: str,feature: str,) -> str: + """Returns a fully-qualified feature string.""" + return "projects/{project}/locations/{location}/features/{feature}".format(project=project, location=location, feature=feature, ) + + @staticmethod + def parse_feature_path(path: str) -> Dict[str,str]: + """Parses a feature path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/features/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def membership_path(project: str,location: str,membership: str,) -> str: + """Returns a fully-qualified membership string.""" + return "projects/{project}/locations/{location}/memberships/{membership}".format(project=project, location=location, membership=membership, ) + + @staticmethod + def parse_membership_path(path: str) -> Dict[str,str]: + """Parses a membership path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/memberships/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, GkeHubTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gke hub client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, GkeHubTransport]): The + transport to use. 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. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, GkeHubTransport): + # transport is a GkeHubTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_memberships(self, + request: Optional[Union[service.ListMembershipsRequest, 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.ListMembershipsPager: + r"""Lists Memberships in a given project and location. + + .. 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 gkehub_v1 + + def sample_list_memberships(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListMembershipsRequest, dict]): + The request object. Request message for ``GkeHub.ListMemberships`` method. + parent (str): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` + list memberships in all the regions. + + 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.gkehub_v1.services.gke_hub.pagers.ListMembershipsPager: + Response message for the GkeHub.ListMemberships method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.ListMembershipsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListMembershipsRequest): + request = service.ListMembershipsRequest(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_memberships] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembershipsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_features(self, + request: Optional[Union[service.ListFeaturesRequest, 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.ListFeaturesPager: + r"""Lists Features in a given project and location. + + .. 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 gkehub_v1 + + def sample_list_features(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFeaturesRequest( + ) + + # Make the request + page_result = client.list_features(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListFeaturesRequest, dict]): + The request object. Request message for ``GkeHub.ListFeatures`` method. + parent (str): + Required. The parent (project and location) where the + Features will 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.gkehub_v1.services.gke_hub.pagers.ListFeaturesPager: + Response message for the GkeHub.ListFeatures method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.ListFeaturesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListFeaturesRequest): + request = service.ListFeaturesRequest(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_features] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFeaturesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership(self, + request: Optional[Union[service.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Gets the details of a Membership. + + .. 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 gkehub_v1 + + def sample_get_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetMembershipRequest, dict]): + The request object. Request message for ``GkeHub.GetMembership`` method. + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.gkehub_v1.types.Membership: + Membership contains information about + a member cluster. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.GetMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetMembershipRequest): + request = service.GetMembershipRequest(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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_feature(self, + request: Optional[Union[service.GetFeatureRequest, 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]] = (), + ) -> feature.Feature: + r"""Gets details of a single Feature. + + .. 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 gkehub_v1 + + def sample_get_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFeatureRequest( + ) + + # Make the request + response = client.get_feature(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetFeatureRequest, dict]): + The request object. Request message for ``GkeHub.GetFeature`` method. + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*`` + + 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.gkehub_v1.types.Feature: + Feature represents the settings and + status of any Hub Feature. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.GetFeatureRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetFeatureRequest): + request = service.GetFeatureRequest(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_feature] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_membership(self, + request: Optional[Union[service.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[membership.Membership] = None, + membership_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 Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + .. 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 gkehub_v1 + + def sample_create_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateMembershipRequest, dict]): + The request object. Request message for the ``GkeHub.CreateMembership`` + method. + parent (str): + Required. The parent (project and location) where the + Memberships will 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. + resource (google.cloud.gkehub_v1.types.Membership): + Required. The membership to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_id (str): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``membership_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.gkehub_v1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, membership_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.CreateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateMembershipRequest): + request = service.CreateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if membership_id is not None: + request.membership_id = membership_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + membership.Membership, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_feature(self, + request: Optional[Union[service.CreateFeatureRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[feature.Feature] = None, + feature_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"""Adds a new Feature. + + .. 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 gkehub_v1 + + def sample_create_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFeatureRequest( + ) + + # Make the request + operation = client.create_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateFeatureRequest, dict]): + The request object. Request message for the ``GkeHub.CreateFeature`` method. + parent (str): + Required. The parent (project and location) where the + Feature will 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. + resource (google.cloud.gkehub_v1.types.Feature): + The Feature resource to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + feature_id (str): + The ID of the feature to create. + This corresponds to the ``feature_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.gkehub_v1.types.Feature` Feature + represents the settings and status of any Hub Feature. + + """ + # 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, resource, feature_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.CreateFeatureRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateFeatureRequest): + request = service.CreateFeatureRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if feature_id is not None: + request.feature_id = feature_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_feature] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + feature.Feature, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_membership(self, + request: Optional[Union[service.DeleteMembershipRequest, 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"""Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + .. 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 gkehub_v1 + + def sample_delete_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteMembershipRequest, dict]): + The request object. Request message for ``GkeHub.DeleteMembership`` method. + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteMembershipRequest): + request = service.DeleteMembershipRequest(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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_feature(self, + request: Optional[Union[service.DeleteFeatureRequest, 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"""Removes a Feature. + + .. 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 gkehub_v1 + + def sample_delete_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFeatureRequest( + ) + + # Make the request + operation = client.delete_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteFeatureRequest, dict]): + The request object. Request message for ``GkeHub.DeleteFeature`` method. + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.DeleteFeatureRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DeleteFeatureRequest): + request = service.DeleteFeatureRequest(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_feature] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_membership(self, + request: Optional[Union[service.UpdateMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[membership.Membership] = 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 an existing Membership. + + .. 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 gkehub_v1 + + def sample_update_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateMembershipRequest, dict]): + The request object. Request message for ``GkeHub.UpdateMembership`` method. + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.gkehub_v1.types.Membership): + Required. Only fields specified in update_mask are + updated. If you specify a field in the update_mask but + don't specify its value here that field will be deleted. + If you are updating a map field, set the value of a key + to null or empty string to delete the key from the map. + It's not possible to update a key's value to the empty + string. If you specify the update_mask to be a special + path "*", fully replaces all user-modifiable fields to + match ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. + 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.gkehub_v1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.UpdateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateMembershipRequest): + request = service.UpdateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + 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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + membership.Membership, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_feature(self, + request: Optional[Union[service.UpdateFeatureRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[feature.Feature] = 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 an existing Feature. + + .. 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 gkehub_v1 + + def sample_update_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFeatureRequest( + ) + + # Make the request + operation = client.update_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateFeatureRequest, dict]): + The request object. Request message for ``GkeHub.UpdateFeature`` method. + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.gkehub_v1.types.Feature): + Only fields specified in update_mask are updated. If you + specify a field in the update_mask but don't specify its + value here that field will be deleted. If you are + updating a map field, set the value of a key to null or + empty string to delete the key from the map. It's not + possible to update a key's value to the empty string. If + you specify the update_mask to be a special path "*", + fully replaces all user-modifiable fields to match + ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask of fields to update. + 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.gkehub_v1.types.Feature` Feature + represents the settings and status of any Hub Feature. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a service.UpdateFeatureRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateFeatureRequest): + request = service.UpdateFeatureRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + 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_feature] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + feature.Feature, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_connect_manifest(self, + request: Optional[Union[service.GenerateConnectManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateConnectManifestResponse: + r"""Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + .. 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 gkehub_v1 + + def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GenerateConnectManifestRequest, dict]): + The request object. Request message for ``GkeHub.GenerateConnectManifest`` + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1.types.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.GenerateConnectManifestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateConnectManifestRequest): + request = service.GenerateConnectManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_connect_manifest] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "GkeHubClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "GkeHubClient", +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/pagers.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/pagers.py new file mode 100644 index 0000000..d0ca301 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/pagers.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service + + +class ListMembershipsPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipsResponse` + 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[..., service.ListMembershipsResponse], + request: service.ListMembershipsRequest, + response: service.ListMembershipsResponse, + *, + 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.gkehub_v1.types.ListMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[membership.Membership]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMembershipsAsyncPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipsResponse` + 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[service.ListMembershipsResponse]], + request: service.ListMembershipsRequest, + response: service.ListMembershipsResponse, + *, + 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.gkehub_v1.types.ListMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[membership.Membership]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFeaturesPager: + """A pager for iterating through ``list_features`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListFeaturesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFeatures`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListFeaturesResponse` + 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[..., service.ListFeaturesResponse], + request: service.ListFeaturesRequest, + response: service.ListFeaturesResponse, + *, + 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.gkehub_v1.types.ListFeaturesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListFeaturesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListFeaturesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListFeaturesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[feature.Feature]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFeaturesAsyncPager: + """A pager for iterating through ``list_features`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListFeaturesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFeatures`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListFeaturesResponse` + 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[service.ListFeaturesResponse]], + request: service.ListFeaturesRequest, + response: service.ListFeaturesResponse, + *, + 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.gkehub_v1.types.ListFeaturesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListFeaturesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListFeaturesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListFeaturesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[feature.Feature]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + 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/v1/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py new file mode 100644 index 0000000..19a299b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GkeHubTransport +from .grpc import GkeHubGrpcTransport +from .grpc_asyncio import GkeHubGrpcAsyncIOTransport +from .rest import GkeHubRestTransport +from .rest import GkeHubRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GkeHubTransport]] +_transport_registry['grpc'] = GkeHubGrpcTransport +_transport_registry['grpc_asyncio'] = GkeHubGrpcAsyncIOTransport +_transport_registry['rest'] = GkeHubRestTransport + +__all__ = ( + 'GkeHubTransport', + 'GkeHubGrpcTransport', + 'GkeHubGrpcAsyncIOTransport', + 'GkeHubRestTransport', + 'GkeHubRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/base.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/base.py new file mode 100644 index 0000000..c0cbbbf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/base.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_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.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class GkeHubTransport(abc.ABC): + """Abstract transport class for GkeHub.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'gkehub.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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_memberships: gapic_v1.method.wrap_method( + self.list_memberships, + default_timeout=None, + client_info=client_info, + ), + self.list_features: gapic_v1.method.wrap_method( + self.list_features, + default_timeout=None, + client_info=client_info, + ), + self.get_membership: gapic_v1.method.wrap_method( + self.get_membership, + default_timeout=None, + client_info=client_info, + ), + self.get_feature: gapic_v1.method.wrap_method( + self.get_feature, + default_timeout=None, + client_info=client_info, + ), + self.create_membership: gapic_v1.method.wrap_method( + self.create_membership, + default_timeout=None, + client_info=client_info, + ), + self.create_feature: gapic_v1.method.wrap_method( + self.create_feature, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership: gapic_v1.method.wrap_method( + self.delete_membership, + default_timeout=None, + client_info=client_info, + ), + self.delete_feature: gapic_v1.method.wrap_method( + self.delete_feature, + default_timeout=None, + client_info=client_info, + ), + self.update_membership: gapic_v1.method.wrap_method( + self.update_membership, + default_timeout=None, + client_info=client_info, + ), + self.update_feature: gapic_v1.method.wrap_method( + self.update_feature, + default_timeout=None, + client_info=client_info, + ), + self.generate_connect_manifest: gapic_v1.method.wrap_method( + self.generate_connect_manifest, + 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_memberships(self) -> Callable[ + [service.ListMembershipsRequest], + Union[ + service.ListMembershipsResponse, + Awaitable[service.ListMembershipsResponse] + ]]: + raise NotImplementedError() + + @property + def list_features(self) -> Callable[ + [service.ListFeaturesRequest], + Union[ + service.ListFeaturesResponse, + Awaitable[service.ListFeaturesResponse] + ]]: + raise NotImplementedError() + + @property + def get_membership(self) -> Callable[ + [service.GetMembershipRequest], + Union[ + membership.Membership, + Awaitable[membership.Membership] + ]]: + raise NotImplementedError() + + @property + def get_feature(self) -> Callable[ + [service.GetFeatureRequest], + Union[ + feature.Feature, + Awaitable[feature.Feature] + ]]: + raise NotImplementedError() + + @property + def create_membership(self) -> Callable[ + [service.CreateMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_feature(self) -> Callable[ + [service.CreateFeatureRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_membership(self) -> Callable[ + [service.DeleteMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_feature(self) -> Callable[ + [service.DeleteFeatureRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_membership(self) -> Callable[ + [service.UpdateMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_feature(self) -> Callable[ + [service.UpdateFeatureRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_connect_manifest(self) -> Callable[ + [service.GenerateConnectManifestRequest], + Union[ + service.GenerateConnectManifestResponse, + Awaitable[service.GenerateConnectManifestResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'GkeHubTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py new file mode 100644 index 0000000..ff1c95d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py @@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +from google.longrunning import operations_pb2 # type: ignore +from .base import GkeHubTransport, DEFAULT_CLIENT_INFO + + +class GkeHubGrpcTransport(GkeHubTransport): + """gRPC backend transport for GkeHub. + + The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends 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 = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'gkehub.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_memberships(self) -> Callable[ + [service.ListMembershipsRequest], + service.ListMembershipsResponse]: + r"""Return a callable for the list memberships method over gRPC. + + Lists Memberships in a given project and location. + + Returns: + Callable[[~.ListMembershipsRequest], + ~.ListMembershipsResponse]: + 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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/ListMemberships', + request_serializer=service.ListMembershipsRequest.serialize, + response_deserializer=service.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def list_features(self) -> Callable[ + [service.ListFeaturesRequest], + service.ListFeaturesResponse]: + r"""Return a callable for the list features method over gRPC. + + Lists Features in a given project and location. + + Returns: + Callable[[~.ListFeaturesRequest], + ~.ListFeaturesResponse]: + 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_features' not in self._stubs: + self._stubs['list_features'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/ListFeatures', + request_serializer=service.ListFeaturesRequest.serialize, + response_deserializer=service.ListFeaturesResponse.deserialize, + ) + return self._stubs['list_features'] + + @property + def get_membership(self) -> Callable[ + [service.GetMembershipRequest], + membership.Membership]: + r"""Return a callable for the get membership method over gRPC. + + Gets the details of a Membership. + + Returns: + Callable[[~.GetMembershipRequest], + ~.Membership]: + 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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GetMembership', + request_serializer=service.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def get_feature(self) -> Callable[ + [service.GetFeatureRequest], + feature.Feature]: + r"""Return a callable for the get feature method over gRPC. + + Gets details of a single Feature. + + Returns: + Callable[[~.GetFeatureRequest], + ~.Feature]: + 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_feature' not in self._stubs: + self._stubs['get_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GetFeature', + request_serializer=service.GetFeatureRequest.serialize, + response_deserializer=feature.Feature.deserialize, + ) + return self._stubs['get_feature'] + + @property + def create_membership(self) -> Callable[ + [service.CreateMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the create membership method over gRPC. + + Creates a new Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + Returns: + Callable[[~.CreateMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/CreateMembership', + request_serializer=service.CreateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_membership'] + + @property + def create_feature(self) -> Callable[ + [service.CreateFeatureRequest], + operations_pb2.Operation]: + r"""Return a callable for the create feature method over gRPC. + + Adds a new Feature. + + Returns: + Callable[[~.CreateFeatureRequest], + ~.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_feature' not in self._stubs: + self._stubs['create_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/CreateFeature', + request_serializer=service.CreateFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_feature'] + + @property + def delete_membership(self) -> Callable[ + [service.DeleteMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete membership method over gRPC. + + Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + Returns: + Callable[[~.DeleteMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/DeleteMembership', + request_serializer=service.DeleteMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_membership'] + + @property + def delete_feature(self) -> Callable[ + [service.DeleteFeatureRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete feature method over gRPC. + + Removes a Feature. + + Returns: + Callable[[~.DeleteFeatureRequest], + ~.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_feature' not in self._stubs: + self._stubs['delete_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/DeleteFeature', + request_serializer=service.DeleteFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_feature'] + + @property + def update_membership(self) -> Callable[ + [service.UpdateMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the update membership method over gRPC. + + Updates an existing Membership. + + Returns: + Callable[[~.UpdateMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/UpdateMembership', + request_serializer=service.UpdateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_membership'] + + @property + def update_feature(self) -> Callable[ + [service.UpdateFeatureRequest], + operations_pb2.Operation]: + r"""Return a callable for the update feature method over gRPC. + + Updates an existing Feature. + + Returns: + Callable[[~.UpdateFeatureRequest], + ~.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_feature' not in self._stubs: + self._stubs['update_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/UpdateFeature', + request_serializer=service.UpdateFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_feature'] + + @property + def generate_connect_manifest(self) -> Callable[ + [service.GenerateConnectManifestRequest], + service.GenerateConnectManifestResponse]: + r"""Return a callable for the generate connect manifest method over gRPC. + + Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + Returns: + Callable[[~.GenerateConnectManifestRequest], + ~.GenerateConnectManifestResponse]: + 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_connect_manifest' not in self._stubs: + self._stubs['generate_connect_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GenerateConnectManifest', + request_serializer=service.GenerateConnectManifestRequest.serialize, + response_deserializer=service.GenerateConnectManifestResponse.deserialize, + ) + return self._stubs['generate_connect_manifest'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'GkeHubGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py new file mode 100644 index 0000000..64acfa0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py @@ -0,0 +1,572 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 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.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +from google.longrunning import operations_pb2 # type: ignore +from .base import GkeHubTransport, DEFAULT_CLIENT_INFO +from .grpc import GkeHubGrpcTransport + + +class GkeHubGrpcAsyncIOTransport(GkeHubTransport): + """gRPC AsyncIO backend transport for GkeHub. + + The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends 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 = 'gkehub.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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_memberships(self) -> Callable[ + [service.ListMembershipsRequest], + Awaitable[service.ListMembershipsResponse]]: + r"""Return a callable for the list memberships method over gRPC. + + Lists Memberships in a given project and location. + + Returns: + Callable[[~.ListMembershipsRequest], + Awaitable[~.ListMembershipsResponse]]: + 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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/ListMemberships', + request_serializer=service.ListMembershipsRequest.serialize, + response_deserializer=service.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def list_features(self) -> Callable[ + [service.ListFeaturesRequest], + Awaitable[service.ListFeaturesResponse]]: + r"""Return a callable for the list features method over gRPC. + + Lists Features in a given project and location. + + Returns: + Callable[[~.ListFeaturesRequest], + Awaitable[~.ListFeaturesResponse]]: + 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_features' not in self._stubs: + self._stubs['list_features'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/ListFeatures', + request_serializer=service.ListFeaturesRequest.serialize, + response_deserializer=service.ListFeaturesResponse.deserialize, + ) + return self._stubs['list_features'] + + @property + def get_membership(self) -> Callable[ + [service.GetMembershipRequest], + Awaitable[membership.Membership]]: + r"""Return a callable for the get membership method over gRPC. + + Gets the details of a Membership. + + Returns: + Callable[[~.GetMembershipRequest], + Awaitable[~.Membership]]: + 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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GetMembership', + request_serializer=service.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def get_feature(self) -> Callable[ + [service.GetFeatureRequest], + Awaitable[feature.Feature]]: + r"""Return a callable for the get feature method over gRPC. + + Gets details of a single Feature. + + Returns: + Callable[[~.GetFeatureRequest], + Awaitable[~.Feature]]: + 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_feature' not in self._stubs: + self._stubs['get_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GetFeature', + request_serializer=service.GetFeatureRequest.serialize, + response_deserializer=feature.Feature.deserialize, + ) + return self._stubs['get_feature'] + + @property + def create_membership(self) -> Callable[ + [service.CreateMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create membership method over gRPC. + + Creates a new Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + Returns: + Callable[[~.CreateMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/CreateMembership', + request_serializer=service.CreateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_membership'] + + @property + def create_feature(self) -> Callable[ + [service.CreateFeatureRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create feature method over gRPC. + + Adds a new Feature. + + Returns: + Callable[[~.CreateFeatureRequest], + 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_feature' not in self._stubs: + self._stubs['create_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/CreateFeature', + request_serializer=service.CreateFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_feature'] + + @property + def delete_membership(self) -> Callable[ + [service.DeleteMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete membership method over gRPC. + + Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + Returns: + Callable[[~.DeleteMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/DeleteMembership', + request_serializer=service.DeleteMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_membership'] + + @property + def delete_feature(self) -> Callable[ + [service.DeleteFeatureRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete feature method over gRPC. + + Removes a Feature. + + Returns: + Callable[[~.DeleteFeatureRequest], + 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_feature' not in self._stubs: + self._stubs['delete_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/DeleteFeature', + request_serializer=service.DeleteFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_feature'] + + @property + def update_membership(self) -> Callable[ + [service.UpdateMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update membership method over gRPC. + + Updates an existing Membership. + + Returns: + Callable[[~.UpdateMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/UpdateMembership', + request_serializer=service.UpdateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_membership'] + + @property + def update_feature(self) -> Callable[ + [service.UpdateFeatureRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update feature method over gRPC. + + Updates an existing Feature. + + Returns: + Callable[[~.UpdateFeatureRequest], + 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_feature' not in self._stubs: + self._stubs['update_feature'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/UpdateFeature', + request_serializer=service.UpdateFeatureRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_feature'] + + @property + def generate_connect_manifest(self) -> Callable[ + [service.GenerateConnectManifestRequest], + Awaitable[service.GenerateConnectManifestResponse]]: + r"""Return a callable for the generate connect manifest method over gRPC. + + Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + Returns: + Callable[[~.GenerateConnectManifestRequest], + Awaitable[~.GenerateConnectManifestResponse]]: + 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_connect_manifest' not in self._stubs: + self._stubs['generate_connect_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1.GkeHub/GenerateConnectManifest', + request_serializer=service.GenerateConnectManifestRequest.serialize, + response_deserializer=service.GenerateConnectManifestResponse.deserialize, + ) + return self._stubs['generate_connect_manifest'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'GkeHubGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py new file mode 100644 index 0000000..7afd832 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py @@ -0,0 +1,1472 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +from google.longrunning import operations_pb2 # type: ignore + +from .base import GkeHubTransport, 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 GkeHubRestInterceptor: + """Interceptor for GkeHub. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the GkeHubRestTransport. + + .. code-block:: python + class MyCustomGkeHubInterceptor(GkeHubRestInterceptor): + def pre_create_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_connect_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_connect_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_features(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_features(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_feature(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_feature(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GkeHubRestTransport(interceptor=MyCustomGkeHubInterceptor()) + client = GkeHubClient(transport=transport) + + + """ + def pre_create_feature(self, request: service.CreateFeatureRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_create_feature(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_create_membership(self, request: service.CreateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_create_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_delete_feature(self, request: service.DeleteFeatureRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_delete_feature(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_delete_membership(self, request: service.DeleteMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_delete_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_generate_connect_manifest(self, request: service.GenerateConnectManifestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateConnectManifestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_generate_connect_manifest(self, response: service.GenerateConnectManifestResponse) -> service.GenerateConnectManifestResponse: + """Post-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_get_feature(self, request: service.GetFeatureRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_feature(self, response: feature.Feature) -> feature.Feature: + """Post-rpc interceptor for get_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_get_membership(self, request: service.GetMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_membership(self, response: membership.Membership) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_list_features(self, request: service.ListFeaturesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListFeaturesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_features + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_features(self, response: service.ListFeaturesResponse) -> service.ListFeaturesResponse: + """Post-rpc interceptor for list_features + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_list_memberships(self, request: service.ListMembershipsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_memberships(self, response: service.ListMembershipsResponse) -> service.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_update_feature(self, request: service.UpdateFeatureRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateFeatureRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_feature(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_feature + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + def pre_update_membership(self, request: service.UpdateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GkeHubRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GkeHubRestInterceptor + + +class GkeHubRestTransport(GkeHubTransport): + """REST backend transport for GkeHub. + + The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[GkeHubRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GkeHubRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFeature(GkeHubRestStub): + def __hash__(self): + return hash("CreateFeature") + + def __call__(self, + request: service.CreateFeatureRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create feature method over HTTP. + + Args: + request (~.service.CreateFeatureRequest): + The request object. Request message for the ``GkeHub.CreateFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/features', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_create_feature(request, metadata) + pb_request = service.CreateFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_feature(resp) + return resp + + class _CreateMembership(GkeHubRestStub): + def __hash__(self): + return hash("CreateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "membershipId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.CreateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create membership method over HTTP. + + Args: + request (~.service.CreateMembershipRequest): + The request object. Request message for the ``GkeHub.CreateMembership`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/memberships', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_create_membership(request, metadata) + pb_request = service.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _DeleteFeature(GkeHubRestStub): + def __hash__(self): + return hash("DeleteFeature") + + def __call__(self, + request: service.DeleteFeatureRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete feature method over HTTP. + + Args: + request (~.service.DeleteFeatureRequest): + The request object. Request message for ``GkeHub.DeleteFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/features/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_feature(request, metadata) + pb_request = service.DeleteFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_feature(resp) + return resp + + class _DeleteMembership(GkeHubRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: service.DeleteMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete membership method over HTTP. + + Args: + request (~.service.DeleteMembershipRequest): + The request object. Request message for ``GkeHub.DeleteMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/memberships/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_membership(request, metadata) + pb_request = service.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _GenerateConnectManifest(GkeHubRestStub): + def __hash__(self): + return hash("GenerateConnectManifest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: service.GenerateConnectManifestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.GenerateConnectManifestResponse: + r"""Call the generate connect manifest method over HTTP. + + Args: + request (~.service.GenerateConnectManifestRequest): + The request object. Request message for ``GkeHub.GenerateConnectManifest`` + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest', + }, + ] + request, metadata = self._interceptor.pre_generate_connect_manifest(request, metadata) + pb_request = service.GenerateConnectManifestRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateConnectManifestResponse() + pb_resp = service.GenerateConnectManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_connect_manifest(resp) + return resp + + class _GetFeature(GkeHubRestStub): + def __hash__(self): + return hash("GetFeature") + + def __call__(self, + request: service.GetFeatureRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> feature.Feature: + r"""Call the get feature method over HTTP. + + Args: + request (~.service.GetFeatureRequest): + The request object. Request message for ``GkeHub.GetFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.feature.Feature: + Feature represents the settings and + status of any Hub Feature. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/features/*}', + }, + ] + request, metadata = self._interceptor.pre_get_feature(request, metadata) + pb_request = service.GetFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = feature.Feature() + pb_resp = feature.Feature.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_feature(resp) + return resp + + class _GetMembership(GkeHubRestStub): + def __hash__(self): + return hash("GetMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: service.GetMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.service.GetMembershipRequest): + The request object. Request message for ``GkeHub.GetMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.Membership: + Membership contains information about + a member cluster. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/memberships/*}', + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = service.GetMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _ListFeatures(GkeHubRestStub): + def __hash__(self): + return hash("ListFeatures") + + def __call__(self, + request: service.ListFeaturesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListFeaturesResponse: + r"""Call the list features method over HTTP. + + Args: + request (~.service.ListFeaturesRequest): + The request object. Request message for ``GkeHub.ListFeatures`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListFeaturesResponse: + Response message for the ``GkeHub.ListFeatures`` method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/features', + }, + ] + request, metadata = self._interceptor.pre_list_features(request, metadata) + pb_request = service.ListFeaturesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListFeaturesResponse() + pb_resp = service.ListFeaturesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_features(resp) + return resp + + class _ListMemberships(GkeHubRestStub): + def __hash__(self): + return hash("ListMemberships") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: service.ListMembershipsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.service.ListMembershipsRequest): + The request object. Request message for ``GkeHub.ListMemberships`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListMembershipsResponse: + Response message for the ``GkeHub.ListMemberships`` + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/memberships', + }, + ] + request, metadata = self._interceptor.pre_list_memberships(request, metadata) + pb_request = service.ListMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListMembershipsResponse() + pb_resp = service.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _UpdateFeature(GkeHubRestStub): + def __hash__(self): + return hash("UpdateFeature") + + def __call__(self, + request: service.UpdateFeatureRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update feature method over HTTP. + + Args: + request (~.service.UpdateFeatureRequest): + The request object. Request message for ``GkeHub.UpdateFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/features/*}', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_update_feature(request, metadata) + pb_request = service.UpdateFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_feature(resp) + return resp + + class _UpdateMembership(GkeHubRestStub): + def __hash__(self): + return hash("UpdateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: service.UpdateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update membership method over HTTP. + + Args: + request (~.service.UpdateMembershipRequest): + The request object. Request message for ``GkeHub.UpdateMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/memberships/*}', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_update_membership(request, metadata) + pb_request = service.UpdateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_membership(resp) + return resp + + @property + def create_feature(self) -> Callable[ + [service.CreateFeatureRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_membership(self) -> Callable[ + [service.CreateMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_feature(self) -> Callable[ + [service.DeleteFeatureRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership(self) -> Callable[ + [service.DeleteMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_connect_manifest(self) -> Callable[ + [service.GenerateConnectManifestRequest], + service.GenerateConnectManifestResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateConnectManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_feature(self) -> Callable[ + [service.GetFeatureRequest], + feature.Feature]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership(self) -> Callable[ + [service.GetMembershipRequest], + membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_features(self) -> Callable[ + [service.ListFeaturesRequest], + service.ListFeaturesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFeatures(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships(self) -> Callable[ + [service.ListMembershipsRequest], + service.ListMembershipsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_feature(self) -> Callable[ + [service.UpdateFeatureRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFeature(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership(self) -> Callable[ + [service.UpdateMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'GkeHubRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/__init__.py new file mode 100644 index 0000000..586ca5d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/__init__.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .feature import ( + CommonFeatureSpec, + CommonFeatureState, + Feature, + FeatureResourceState, + FeatureState, + MembershipFeatureSpec, + MembershipFeatureState, +) +from .membership import ( + Authority, + GkeCluster, + KubernetesMetadata, + KubernetesResource, + Membership, + MembershipEndpoint, + MembershipState, + MonitoringConfig, + ResourceManifest, + ResourceOptions, +) +from .service import ( + ConnectAgentResource, + CreateFeatureRequest, + CreateMembershipRequest, + DeleteFeatureRequest, + DeleteMembershipRequest, + GenerateConnectManifestRequest, + GenerateConnectManifestResponse, + GetFeatureRequest, + GetMembershipRequest, + ListFeaturesRequest, + ListFeaturesResponse, + ListMembershipsRequest, + ListMembershipsResponse, + OperationMetadata, + TypeMeta, + UpdateFeatureRequest, + UpdateMembershipRequest, +) + +__all__ = ( + 'CommonFeatureSpec', + 'CommonFeatureState', + 'Feature', + 'FeatureResourceState', + 'FeatureState', + 'MembershipFeatureSpec', + 'MembershipFeatureState', + 'Authority', + 'GkeCluster', + 'KubernetesMetadata', + 'KubernetesResource', + 'Membership', + 'MembershipEndpoint', + 'MembershipState', + 'MonitoringConfig', + 'ResourceManifest', + 'ResourceOptions', + 'ConnectAgentResource', + 'CreateFeatureRequest', + 'CreateMembershipRequest', + 'DeleteFeatureRequest', + 'DeleteMembershipRequest', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'GetFeatureRequest', + 'GetMembershipRequest', + 'ListFeaturesRequest', + 'ListFeaturesResponse', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'OperationMetadata', + 'TypeMeta', + 'UpdateFeatureRequest', + 'UpdateMembershipRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/types/feature.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/feature.py new file mode 100644 index 0000000..fd6c5a7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/feature.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloud.gkehub.configmanagement.v1 import configmanagement_pb2 # type: ignore +from google.cloud.gkehub.multiclusteringress.v1 import multiclusteringress_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.v1', + manifest={ + 'Feature', + 'FeatureResourceState', + 'FeatureState', + 'CommonFeatureSpec', + 'CommonFeatureState', + 'MembershipFeatureSpec', + 'MembershipFeatureState', + }, +) + + +class Feature(proto.Message): + r"""Feature represents the settings and status of any Hub + Feature. + + Attributes: + name (str): + Output only. The full, unique name of this Feature resource + in the format ``projects/*/locations/*/features/*``. + labels (MutableMapping[str, str]): + GCP labels for this Feature. + resource_state (google.cloud.gkehub_v1.types.FeatureResourceState): + Output only. State of the Feature resource + itself. + spec (google.cloud.gkehub_v1.types.CommonFeatureSpec): + Optional. Hub-wide Feature configuration. If + this Feature does not support any Hub-wide + configuration, this field may be unused. + membership_specs (MutableMapping[str, google.cloud.gkehub_v1.types.MembershipFeatureSpec]): + Optional. Membership-specific configuration + for this Feature. If this Feature does not + support any per-Membership configuration, this + field may be unused. + + The keys indicate which Membership the + configuration is for, in the form: + + projects/{p}/locations/{l}/memberships/{m} + + Where {p} is the project, {l} is a valid + location and {m} is a valid Membership in this + project at that location. {p} WILL match the + Feature's project. + + {p} will always be returned as the project + number, but the project ID is also accepted + during input. If the same Membership is + specified in the map twice (using the project ID + form, and the project number form), exactly ONE + of the entries will be saved, with no guarantees + as to which. For this reason, it is recommended + the same format be used for all entries when + mutating a Feature. + state (google.cloud.gkehub_v1.types.CommonFeatureState): + Output only. The Hub-wide Feature state. + membership_states (MutableMapping[str, google.cloud.gkehub_v1.types.MembershipFeatureState]): + Output only. Membership-specific Feature + status. If this Feature does report any + per-Membership status, this field may be unused. + + The keys indicate which Membership the state is + for, in the form: + + projects/{p}/locations/{l}/memberships/{m} + + Where {p} is the project number, {l} is a valid + location and {m} is a valid Membership in this + project at that location. {p} MUST match the + Feature's project number. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Feature resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Feature resource was + last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Feature resource was + deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + resource_state: 'FeatureResourceState' = proto.Field( + proto.MESSAGE, + number=3, + message='FeatureResourceState', + ) + spec: 'CommonFeatureSpec' = proto.Field( + proto.MESSAGE, + number=4, + message='CommonFeatureSpec', + ) + membership_specs: MutableMapping[str, 'MembershipFeatureSpec'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message='MembershipFeatureSpec', + ) + state: 'CommonFeatureState' = proto.Field( + proto.MESSAGE, + number=6, + message='CommonFeatureState', + ) + membership_states: MutableMapping[str, 'MembershipFeatureState'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message='MembershipFeatureState', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class FeatureResourceState(proto.Message): + r"""FeatureResourceState describes the state of a Feature *resource* in + the GkeHub API. See ``FeatureState`` for the "running state" of the + Feature in the Hub and across Memberships. + + Attributes: + state (google.cloud.gkehub_v1.types.FeatureResourceState.State): + The current state of the Feature resource in + the Hub API. + """ + class State(proto.Enum): + r"""State describes the lifecycle status of a Feature. + + Values: + STATE_UNSPECIFIED (0): + State is unknown or not set. + ENABLING (1): + The Feature is being enabled, and the Feature + resource is being created. Once complete, the + corresponding Feature will be enabled in this + Hub. + ACTIVE (2): + The Feature is enabled in this Hub, and the + Feature resource is fully available. + DISABLING (3): + The Feature is being disabled in this Hub, + and the Feature resource is being deleted. + UPDATING (4): + The Feature resource is being updated. + SERVICE_UPDATING (5): + The Feature resource is being updated by the + Hub Service. + """ + STATE_UNSPECIFIED = 0 + ENABLING = 1 + ACTIVE = 2 + DISABLING = 3 + UPDATING = 4 + SERVICE_UPDATING = 5 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + + +class FeatureState(proto.Message): + r"""FeatureState describes the high-level state of a Feature. It + may be used to describe a Feature's state at the environ-level, + or per-membershop, depending on the context. + + Attributes: + code (google.cloud.gkehub_v1.types.FeatureState.Code): + The high-level, machine-readable status of + this Feature. + description (str): + A human-readable description of the current + status. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time this status and any related + Feature-specific details were updated. + """ + class Code(proto.Enum): + r"""Code represents a machine-readable, high-level status of the + Feature. + + Values: + CODE_UNSPECIFIED (0): + Unknown or not set. + OK (1): + The Feature is operating normally. + WARNING (2): + The Feature has encountered an issue, and is + operating in a degraded state. The Feature may + need intervention to return to normal operation. + See the description and any associated + Feature-specific details for more information. + ERROR (3): + The Feature is not operating or is in a + severely degraded state. The Feature may need + intervention to return to normal operation. See + the description and any associated + Feature-specific details for more information. + """ + CODE_UNSPECIFIED = 0 + OK = 1 + WARNING = 2 + ERROR = 3 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class CommonFeatureSpec(proto.Message): + r"""CommonFeatureSpec contains Hub-wide configuration information + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + multiclusteringress (google.cloud.gkehub.multiclusteringress.v1.multiclusteringress_pb2.FeatureSpec): + Multicluster Ingress-specific spec. + + This field is a member of `oneof`_ ``feature_spec``. + """ + + multiclusteringress: multiclusteringress_pb2.FeatureSpec = proto.Field( + proto.MESSAGE, + number=102, + oneof='feature_spec', + message=multiclusteringress_pb2.FeatureSpec, + ) + + +class CommonFeatureState(proto.Message): + r"""CommonFeatureState contains Hub-wide Feature status + information. + + Attributes: + state (google.cloud.gkehub_v1.types.FeatureState): + Output only. The "running state" of the + Feature in this Hub. + """ + + state: 'FeatureState' = proto.Field( + proto.MESSAGE, + number=1, + message='FeatureState', + ) + + +class MembershipFeatureSpec(proto.Message): + r"""MembershipFeatureSpec contains configuration information for + a single Membership. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + configmanagement (google.cloud.gkehub.configmanagement.v1.configmanagement_pb2.MembershipSpec): + Config Management-specific spec. + + This field is a member of `oneof`_ ``feature_spec``. + """ + + configmanagement: configmanagement_pb2.MembershipSpec = proto.Field( + proto.MESSAGE, + number=106, + oneof='feature_spec', + message=configmanagement_pb2.MembershipSpec, + ) + + +class MembershipFeatureState(proto.Message): + r"""MembershipFeatureState contains Feature status information + for a single Membership. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + configmanagement (google.cloud.gkehub.configmanagement.v1.configmanagement_pb2.MembershipState): + Config Management-specific state. + + This field is a member of `oneof`_ ``feature_state``. + state (google.cloud.gkehub_v1.types.FeatureState): + The high-level state of this Feature for a + single membership. + """ + + configmanagement: configmanagement_pb2.MembershipState = proto.Field( + proto.MESSAGE, + number=106, + oneof='feature_state', + message=configmanagement_pb2.MembershipState, + ) + state: 'FeatureState' = proto.Field( + proto.MESSAGE, + number=1, + message='FeatureState', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/types/membership.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/membership.py new file mode 100644 index 0000000..10e955f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/membership.py @@ -0,0 +1,605 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.v1', + manifest={ + 'Membership', + 'MembershipEndpoint', + 'KubernetesResource', + 'ResourceOptions', + 'ResourceManifest', + 'GkeCluster', + 'KubernetesMetadata', + 'MonitoringConfig', + 'MembershipState', + 'Authority', + }, +) + + +class Membership(proto.Message): + r"""Membership contains information about a member cluster. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + endpoint (google.cloud.gkehub_v1.types.MembershipEndpoint): + Optional. Endpoint information to reach this + member. + + This field is a member of `oneof`_ ``type``. + name (str): + Output only. The full, unique name of this Membership + resource in the format + ``projects/*/locations/*/memberships/{membership_id}``, set + during creation. + + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + labels (MutableMapping[str, str]): + Optional. Labels for this membership. + description (str): + Output only. Description of this membership, limited to 63 + characters. Must match the regex: + ``[a-zA-Z0-9][a-zA-Z0-9_\-\.\ ]*`` + + This field is present for legacy purposes. + state (google.cloud.gkehub_v1.types.MembershipState): + Output only. State of the Membership + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was last + updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was deleted. + external_id (str): + Optional. An externally-generated and managed ID for this + Membership. This ID may be modified after creation, but this + is not recommended. + + The ID must match the regex: + ``[a-zA-Z0-9][a-zA-Z0-9_\-\.]*`` + + If this Membership represents a Kubernetes cluster, this + value should be set to the UID of the ``kube-system`` + namespace object. + last_connection_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For clusters using Connect, the + timestamp of the most recent connection + established with Google Cloud. This time is + updated every several minutes, not continuously. + For clusters that do not use GKE Connect, or + that have never connected successfully, this + field will be unset. + unique_id (str): + Output only. Google-generated UUID for this resource. This + is unique across all Membership resources. If a Membership + resource is deleted and another resource with the same name + is created, it gets a different unique_id. + authority (google.cloud.gkehub_v1.types.Authority): + Optional. How to identify workloads from this + Membership. See the documentation on Workload + Identity for more details: + + https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity + monitoring_config (google.cloud.gkehub_v1.types.MonitoringConfig): + Optional. The monitoring config information + for this membership. + """ + + endpoint: 'MembershipEndpoint' = proto.Field( + proto.MESSAGE, + number=4, + oneof='type', + message='MembershipEndpoint', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + state: 'MembershipState' = proto.Field( + proto.MESSAGE, + number=5, + message='MembershipState', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + external_id: str = proto.Field( + proto.STRING, + number=9, + ) + last_connection_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + unique_id: str = proto.Field( + proto.STRING, + number=11, + ) + authority: 'Authority' = proto.Field( + proto.MESSAGE, + number=12, + message='Authority', + ) + monitoring_config: 'MonitoringConfig' = proto.Field( + proto.MESSAGE, + number=14, + message='MonitoringConfig', + ) + + +class MembershipEndpoint(proto.Message): + r"""MembershipEndpoint contains information needed to contact a + Kubernetes API, endpoint and any additional Kubernetes metadata. + + Attributes: + gke_cluster (google.cloud.gkehub_v1.types.GkeCluster): + Optional. GKE-specific information. Only + present if this Membership is a GKE cluster. + kubernetes_metadata (google.cloud.gkehub_v1.types.KubernetesMetadata): + Output only. Useful Kubernetes-specific + metadata. + kubernetes_resource (google.cloud.gkehub_v1.types.KubernetesResource): + Optional. The in-cluster Kubernetes Resources that should be + applied for a correctly registered cluster, in the steady + state. These resources: + + - Ensure that the cluster is exclusively registered to one + and only one Hub Membership. + - Propagate Workload Pool Information available in the + Membership Authority field. + - Ensure proper initial configuration of default Hub + Features. + google_managed (bool): + Output only. Whether the lifecycle of this + membership is managed by a google cluster + platform service. + """ + + gke_cluster: 'GkeCluster' = proto.Field( + proto.MESSAGE, + number=1, + message='GkeCluster', + ) + kubernetes_metadata: 'KubernetesMetadata' = proto.Field( + proto.MESSAGE, + number=2, + message='KubernetesMetadata', + ) + kubernetes_resource: 'KubernetesResource' = proto.Field( + proto.MESSAGE, + number=3, + message='KubernetesResource', + ) + google_managed: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class KubernetesResource(proto.Message): + r"""KubernetesResource contains the YAML manifests and + configuration for Membership Kubernetes resources in the + cluster. After CreateMembership or UpdateMembership, these + resources should be re-applied in the cluster. + + Attributes: + membership_cr_manifest (str): + Input only. The YAML representation of the + Membership CR. This field is ignored for GKE + clusters where Hub can read the CR directly. + + Callers should provide the CR that is currently + present in the cluster during CreateMembership + or UpdateMembership, or leave this field empty + if none exists. The CR manifest is used to + validate the cluster has not been registered + with another Membership. + membership_resources (MutableSequence[google.cloud.gkehub_v1.types.ResourceManifest]): + Output only. Additional Kubernetes resources + that need to be applied to the cluster after + Membership creation, and after every update. + + This field is only populated in the Membership + returned from a successful long-running + operation from CreateMembership or + UpdateMembership. It is not populated during + normal GetMembership or ListMemberships + requests. To get the resource manifest after the + initial registration, the caller should make a + UpdateMembership call with an empty field mask. + connect_resources (MutableSequence[google.cloud.gkehub_v1.types.ResourceManifest]): + Output only. The Kubernetes resources for + installing the GKE Connect agent + This field is only populated in the Membership + returned from a successful long-running + operation from CreateMembership or + UpdateMembership. It is not populated during + normal GetMembership or ListMemberships + requests. To get the resource manifest after the + initial registration, the caller should make a + UpdateMembership call with an empty field mask. + resource_options (google.cloud.gkehub_v1.types.ResourceOptions): + Optional. Options for Kubernetes resource + generation. + """ + + membership_cr_manifest: str = proto.Field( + proto.STRING, + number=1, + ) + membership_resources: MutableSequence['ResourceManifest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ResourceManifest', + ) + connect_resources: MutableSequence['ResourceManifest'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ResourceManifest', + ) + resource_options: 'ResourceOptions' = proto.Field( + proto.MESSAGE, + number=4, + message='ResourceOptions', + ) + + +class ResourceOptions(proto.Message): + r"""ResourceOptions represent options for Kubernetes resource + generation. + + Attributes: + connect_version (str): + Optional. The Connect agent version to use for + connect_resources. Defaults to the latest GKE Connect + version. The version must be a currently supported version, + obsolete versions will be rejected. + v1beta1_crd (bool): + Optional. Use ``apiextensions/v1beta1`` instead of + ``apiextensions/v1`` for CustomResourceDefinition resources. + This option should be set for clusters with Kubernetes + apiserver versions <1.16. + k8s_version (str): + Optional. Major version of the Kubernetes cluster. This is + only used to determine which version to use for the + CustomResourceDefinition resources, + ``apiextensions/v1beta1`` or\ ``apiextensions/v1``. + """ + + connect_version: str = proto.Field( + proto.STRING, + number=1, + ) + v1beta1_crd: bool = proto.Field( + proto.BOOL, + number=2, + ) + k8s_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ResourceManifest(proto.Message): + r"""ResourceManifest represents a single Kubernetes resource to + be applied to the cluster. + + Attributes: + manifest (str): + YAML manifest of the resource. + cluster_scoped (bool): + Whether the resource provided in the manifest is + ``cluster_scoped``. If unset, the manifest is assumed to be + namespace scoped. + + This field is used for REST mapping when applying the + resource in a cluster. + """ + + manifest: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_scoped: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class GkeCluster(proto.Message): + r"""GkeCluster contains information specific to GKE clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the Google Cloud + resource for the GKE cluster. For example: + + //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster + + Zonal clusters are also supported. + cluster_missing (bool): + Output only. If cluster_missing is set then it denotes that + the GKE cluster no longer exists in the GKE Control Plane. + """ + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class KubernetesMetadata(proto.Message): + r"""KubernetesMetadata provides informational metadata for + Memberships representing Kubernetes clusters. + + Attributes: + kubernetes_api_server_version (str): + Output only. Kubernetes API server version string as + reported by ``/version``. + node_provider_id (str): + Output only. Node providerID as reported by the first node + in the list of nodes on the Kubernetes endpoint. On + Kubernetes platforms that support zero-node clusters (like + GKE-on-GCP), the node_count will be zero and the + node_provider_id will be empty. + node_count (int): + Output only. Node count as reported by + Kubernetes nodes resources. + vcpu_count (int): + Output only. vCPU count as reported by + Kubernetes nodes resources. + memory_mb (int): + Output only. The total memory capacity as + reported by the sum of all Kubernetes nodes + resources, defined in MB. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which these details were last + updated. This update_time is different from the + Membership-level update_time since EndpointDetails are + updated internally for API consumers. + """ + + kubernetes_api_server_version: str = proto.Field( + proto.STRING, + number=1, + ) + node_provider_id: str = proto.Field( + proto.STRING, + number=2, + ) + node_count: int = proto.Field( + proto.INT32, + number=3, + ) + vcpu_count: int = proto.Field( + proto.INT32, + number=4, + ) + memory_mb: int = proto.Field( + proto.INT32, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=100, + message=timestamp_pb2.Timestamp, + ) + + +class MonitoringConfig(proto.Message): + r"""This field informs Fleet-based applications/services/UIs with + the necessary information for where each underlying Cluster + reports its metrics. + + Attributes: + project_id (str): + Immutable. Project used to report Metrics + location (str): + Immutable. Location used to report Metrics + cluster (str): + Immutable. Cluster name used to report metrics. For Anthos + on VMWare/Baremetal, it would be in format + ``memberClusters/cluster_name``; And for Anthos on + MultiCloud, it would be in format + ``{azureClusters, awsClusters}/cluster_name``. + kubernetes_metrics_prefix (str): + Kubernetes system metrics, if available, are + written to this prefix. This defaults to + kubernetes.io for GKE, and kubernetes.io/anthos + for Anthos eventually. Noted: Anthos MultiCloud + will have kubernetes.io prefix today but will + migration to be under kubernetes.io/anthos + cluster_hash (str): + Immutable. Cluster hash, this is a unique + string generated by google code, which does not + contain any PII, which we can use to reference + the cluster. This is expected to be created by + the monitoring stack and persisted into the + Cluster object as well as to GKE-Hub. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: str = proto.Field( + proto.STRING, + number=3, + ) + kubernetes_metrics_prefix: str = proto.Field( + proto.STRING, + number=4, + ) + cluster_hash: str = proto.Field( + proto.STRING, + number=5, + ) + + +class MembershipState(proto.Message): + r"""MembershipState describes the state of a Membership resource. + + Attributes: + code (google.cloud.gkehub_v1.types.MembershipState.Code): + Output only. The current state of the + Membership resource. + """ + class Code(proto.Enum): + r"""Code describes the state of a Membership resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The cluster is being registered. + READY (2): + The cluster is registered. + DELETING (3): + The cluster is being unregistered. + UPDATING (4): + The Membership is being updated. + SERVICE_UPDATING (5): + The Membership is being updated by the Hub + Service. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + SERVICE_UPDATING = 5 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +class Authority(proto.Message): + r"""Authority encodes how Google will recognize identities from + this Membership. See the workload identity documentation for + more details: + + https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity + + Attributes: + issuer (str): + Optional. A JSON Web Token (JWT) issuer URI. ``issuer`` must + start with ``https://`` and be a valid URL with length <2000 + characters. + + If set, then Google will allow valid OIDC tokens from this + issuer to authenticate within the workload_identity_pool. + OIDC discovery will be performed on this URI to validate + tokens from the issuer. + + Clearing ``issuer`` disables Workload Identity. ``issuer`` + cannot be directly modified; it must be cleared (and + Workload Identity disabled) before using a new issuer (and + re-enabling Workload Identity). + workload_identity_pool (str): + Output only. The name of the workload identity pool in which + ``issuer`` will be recognized. + + There is a single Workload Identity Pool per Hub that is + shared between all Memberships that belong to that Hub. For + a Hub hosted in {PROJECT_ID}, the workload pool format is + ``{PROJECT_ID}.hub.id.goog``, although this is subject to + change in newer versions of this API. + identity_provider (str): + Output only. An identity provider that reflects the + ``issuer`` in the workload identity pool. + oidc_jwks (bytes): + Optional. OIDC verification keys for this Membership in JWKS + format (RFC 7517). + + When this field is set, OIDC discovery will NOT be performed + on ``issuer``, and instead OIDC tokens will be validated + using this field. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + workload_identity_pool: str = proto.Field( + proto.STRING, + number=2, + ) + identity_provider: str = proto.Field( + proto.STRING, + number=3, + ) + oidc_jwks: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/gkehub_v1/types/service.py b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/service.py new file mode 100644 index 0000000..032ec24 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/gkehub_v1/types/service.py @@ -0,0 +1,800 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.v1', + manifest={ + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'GetMembershipRequest', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'UpdateMembershipRequest', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'ConnectAgentResource', + 'TypeMeta', + 'ListFeaturesRequest', + 'ListFeaturesResponse', + 'GetFeatureRequest', + 'CreateFeatureRequest', + 'DeleteFeatureRequest', + 'UpdateFeatureRequest', + 'OperationMetadata', + }, +) + + +class ListMembershipsRequest(proto.Message): + r"""Request message for ``GkeHub.ListMemberships`` method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` list + memberships in all the regions. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListMemberships`` which specifies the position in the list + from where to continue listing the resources. + filter (str): + Optional. Lists Memberships that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. + + Examples: + + - Name is ``bar`` in project ``foo-proj`` and location + ``global``: + + name = + "projects/foo-proj/locations/global/membership/bar" + + - Memberships that have a label called ``foo``: + + labels.foo:\* + + - Memberships that have a label called ``foo`` whose value + is ``bar``: + + labels.foo = bar + + - Memberships in the CREATING state: + + state = CREATING + order_by (str): + Optional. One or more fields to compare and + use to sort the output. 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 ListMembershipsResponse(proto.Message): + r"""Response message for the ``GkeHub.ListMemberships`` method. + + Attributes: + resources (MutableSequence[google.cloud.gkehub_v1.types.Membership]): + The list of matching Memberships. + next_page_token (str): + A token to request the next page of resources from the + ``ListMemberships`` method. The value of an empty string + means that there are no more resources to return. + unreachable (MutableSequence[str]): + List of locations that could not be reached + while fetching this list. + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence[membership.Membership] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=membership.Membership, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetMembershipRequest(proto.Message): + r"""Request message for ``GkeHub.GetMembership`` method. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMembershipRequest(proto.Message): + r"""Request message for the ``GkeHub.CreateMembership`` method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Memberships will be created. Specified in the format + ``projects/*/locations/*``. + membership_id (str): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + resource (google.cloud.gkehub_v1.types.Membership): + Required. The membership to create. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + membership_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource: membership.Membership = proto.Field( + proto.MESSAGE, + number=3, + message=membership.Membership, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteMembershipRequest(proto.Message): + r"""Request message for ``GkeHub.DeleteMembership`` method. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any subresource + from this Membership will also be deleted. + Otherwise, the request will only work if the + Membership has no subresource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class UpdateMembershipRequest(proto.Message): + r"""Request message for ``GkeHub.UpdateMembership`` method. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. + resource (google.cloud.gkehub_v1.types.Membership): + Required. Only fields specified in update_mask are updated. + If you specify a field in the update_mask but don't specify + its value here that field will be deleted. If you are + updating a map field, set the value of a key to null or + empty string to delete the key from the map. It's not + possible to update a key's value to the empty string. If you + specify the update_mask to be a special path "*", fully + replaces all user-modifiable fields to match ``resource``. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + resource: membership.Membership = proto.Field( + proto.MESSAGE, + number=3, + message=membership.Membership, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GenerateConnectManifestRequest(proto.Message): + r"""Request message for ``GkeHub.GenerateConnectManifest`` method. . + + Attributes: + name (str): + Required. The Membership resource name the Agent will + associate with, in the format + ``projects/*/locations/*/memberships/*``. + namespace (str): + Optional. Namespace for GKE Connect agent resources. + Defaults to ``gke-connect``. + + The Connect Agent is authorized automatically when run in + the default namespace. Otherwise, explicit authorization + must be granted with an additional IAM binding. + proxy (bytes): + Optional. URI of a proxy if connectivity from the agent to + gkeconnect.googleapis.com requires the use of a proxy. + Format must be in the form ``http(s)://{proxy_address}``, + depending on the HTTP/HTTPS protocol supported by the proxy. + This will direct the connect agent's outbound traffic + through a HTTP(S) proxy. + version (str): + Optional. The Connect agent version to use. + Defaults to the most current version. + is_upgrade (bool): + Optional. If true, generate the resources for + upgrade only. Some resources generated only for + installation (e.g. secrets) will be excluded. + registry (str): + Optional. The registry to fetch the connect + agent image from. Defaults to gcr.io/gkeconnect. + image_pull_secret_content (bytes): + Optional. The image pull secret content for + the registry, if not public. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + namespace: str = proto.Field( + proto.STRING, + number=2, + ) + proxy: bytes = proto.Field( + proto.BYTES, + number=3, + ) + version: str = proto.Field( + proto.STRING, + number=4, + ) + is_upgrade: bool = proto.Field( + proto.BOOL, + number=5, + ) + registry: str = proto.Field( + proto.STRING, + number=6, + ) + image_pull_secret_content: bytes = proto.Field( + proto.BYTES, + number=7, + ) + + +class GenerateConnectManifestResponse(proto.Message): + r"""GenerateConnectManifestResponse contains manifest information + for installing/upgrading a Connect agent. + + Attributes: + manifest (MutableSequence[google.cloud.gkehub_v1.types.ConnectAgentResource]): + The ordered list of Kubernetes resources that + need to be applied to the cluster for GKE + Connect agent installation/upgrade. + """ + + manifest: MutableSequence['ConnectAgentResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConnectAgentResource', + ) + + +class ConnectAgentResource(proto.Message): + r"""ConnectAgentResource represents a Kubernetes resource + manifest for Connect Agent deployment. + + Attributes: + type_ (google.cloud.gkehub_v1.types.TypeMeta): + Kubernetes type of the resource. + manifest (str): + YAML manifest of the resource. + """ + + type_: 'TypeMeta' = proto.Field( + proto.MESSAGE, + number=1, + message='TypeMeta', + ) + manifest: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TypeMeta(proto.Message): + r"""TypeMeta is the type information needed for content + unmarshalling of Kubernetes resources in the manifest. + + Attributes: + kind (str): + Kind of the resource (e.g. Deployment). + api_version (str): + APIVersion of the resource (e.g. v1). + """ + + kind: str = proto.Field( + proto.STRING, + number=1, + ) + api_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFeaturesRequest(proto.Message): + r"""Request message for ``GkeHub.ListFeatures`` method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*``. + page_size (int): + When requesting a 'page' of resources, ``page_size`` + specifies number of resources to return. If unspecified or + set to 0, all resources will be returned. + page_token (str): + Token returned by previous call to ``ListFeatures`` which + specifies the position in the list from where to continue + listing the resources. + filter (str): + Lists Features that match the filter expression, following + the syntax outlined in https://google.aip.dev/160. + + Examples: + + - Feature with the name "servicemesh" in project + "foo-proj": + + name = + "projects/foo-proj/locations/global/features/servicemesh" + + - Features that have a label called ``foo``: + + labels.foo:\* + + - Features that have a label called ``foo`` whose value is + ``bar``: + + labels.foo = bar + order_by (str): + One or more fields to compare and use to sort + the output. 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 ListFeaturesResponse(proto.Message): + r"""Response message for the ``GkeHub.ListFeatures`` method. + + Attributes: + resources (MutableSequence[google.cloud.gkehub_v1.types.Feature]): + The list of matching Features + next_page_token (str): + A token to request the next page of resources from the + ``ListFeatures`` method. The value of an empty string means + that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence[feature.Feature] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=feature.Feature, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFeatureRequest(proto.Message): + r"""Request message for ``GkeHub.GetFeature`` method. + + Attributes: + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFeatureRequest(proto.Message): + r"""Request message for the ``GkeHub.CreateFeature`` method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Feature will be created. Specified in the format + ``projects/*/locations/*``. + feature_id (str): + The ID of the feature to create. + resource (google.cloud.gkehub_v1.types.Feature): + The Feature resource to create. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + feature_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource: feature.Feature = proto.Field( + proto.MESSAGE, + number=3, + message=feature.Feature, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteFeatureRequest(proto.Message): + r"""Request message for ``GkeHub.DeleteFeature`` method. + + Attributes: + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + force (bool): + If set to true, the delete will ignore any outstanding + resources for this Feature (that is, + ``FeatureState.has_resources`` is set to true). These + resources will NOT be cleaned up or modified in any way. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateFeatureRequest(proto.Message): + r"""Request message for ``GkeHub.UpdateFeature`` method. + + Attributes: + name (str): + Required. The Feature resource name in the format + ``projects/*/locations/*/features/*``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Mask of fields to update. + resource (google.cloud.gkehub_v1.types.Feature): + Only fields specified in update_mask are updated. If you + specify a field in the update_mask but don't specify its + value here that field will be deleted. If you are updating a + map field, set the value of a key to null or empty string to + delete the key from the map. It's not possible to update a + key's value to the empty string. If you specify the + update_mask to be a special path "*", fully replaces all + user-modifiable fields to match ``resource``. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + resource: feature.Feature = proto.Field( + proto.MESSAGE, + number=3, + message=feature.Feature, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_detail (str): + Output only. Human-readable status of the + operation, if any. + cancel_requested (bool): + Output only. 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): + Output only. API version used to start the + operation. + """ + + 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/multiclusteringress/.coveragerc b/owl-bot-staging/v1/multiclusteringress/.coveragerc new file mode 100644 index 0000000..29f7557 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/gkehub/multiclusteringress/__init__.py + google/cloud/gkehub/multiclusteringress/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/v1/multiclusteringress/.flake8 b/owl-bot-staging/v1/multiclusteringress/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/.flake8 @@ -0,0 +1,33 @@ +# -*- 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/v1/multiclusteringress/MANIFEST.in b/owl-bot-staging/v1/multiclusteringress/MANIFEST.in new file mode 100644 index 0000000..6199da3 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/gkehub/multiclusteringress *.py +recursive-include google/cloud/gkehub/multiclusteringress_v1 *.py diff --git a/owl-bot-staging/v1/multiclusteringress/README.rst b/owl-bot-staging/v1/multiclusteringress/README.rst new file mode 100644 index 0000000..a4586cc --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Gkehub Multiclusteringress 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 Gkehub Multiclusteringress 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/v1/multiclusteringress/docs/_static/custom.css b/owl-bot-staging/v1/multiclusteringress/docs/_static/custom.css new file mode 100644 index 0000000..06423be --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1/multiclusteringress/docs/conf.py b/owl-bot-staging/v1/multiclusteringress/docs/conf.py new file mode 100644 index 0000000..1914611 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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-gkehub-multiclusteringress 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-gkehub-multiclusteringress" +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 Gkehub 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-gkehub-multiclusteringress-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-gkehub-multiclusteringress.tex", + u"google-cloud-gkehub-multiclusteringress 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-gkehub-multiclusteringress", + u"Google Cloud Gkehub Multiclusteringress 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-gkehub-multiclusteringress", + u"google-cloud-gkehub-multiclusteringress Documentation", + author, + "google-cloud-gkehub-multiclusteringress", + "GAPIC library for Google Cloud Gkehub Multiclusteringress 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/v1/multiclusteringress/docs/index.rst b/owl-bot-staging/v1/multiclusteringress/docs/index.rst new file mode 100644 index 0000000..ad67e5b --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + multiclusteringress_v1/services + multiclusteringress_v1/types diff --git a/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/services_.rst b/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/services_.rst new file mode 100644 index 0000000..9c56c78 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/services_.rst @@ -0,0 +1,4 @@ +Services for Google Cloud Gkehub Multiclusteringress v1 API +=========================================================== +.. toctree:: + :maxdepth: 2 diff --git a/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/types_.rst b/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/types_.rst new file mode 100644 index 0000000..e3ede26 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/docs/multiclusteringress_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gkehub Multiclusteringress v1 API +======================================================== + +.. automodule:: google.cloud.gkehub.multiclusteringress_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/__init__.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/__init__.py new file mode 100644 index 0000000..f03e769 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/__init__.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub.multiclusteringress import gapic_version as package_version + +__version__ = package_version.__version__ + + + +from google.cloud.gkehub.multiclusteringress_v1.types.multiclusteringress import FeatureSpec + +__all__ = ('FeatureSpec', +) diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/gapic_version.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/py.typed b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/py.typed new file mode 100644 index 0000000..298daf2 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gkehub-multiclusteringress package uses inline types. diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/__init__.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/__init__.py new file mode 100644 index 0000000..7c02aa8 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/__init__.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub.multiclusteringress_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + + +from .types.multiclusteringress import FeatureSpec + +__all__ = ( +'FeatureSpec', +) diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_metadata.json b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_metadata.json new file mode 100644 index 0000000..ad06970 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_metadata.json @@ -0,0 +1,7 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gkehub.multiclusteringress_v1", + "protoPackage": "google.cloud.gkehub.multiclusteringress.v1", + "schema": "1.0" +} diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_version.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/py.typed b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/py.typed new file mode 100644 index 0000000..298daf2 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gkehub-multiclusteringress package uses inline types. diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/services/__init__.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/services/__init__.py new file mode 100644 index 0000000..89a37dc --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/__init__.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/__init__.py new file mode 100644 index 0000000..3a562db --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .multiclusteringress import ( + FeatureSpec, +) + +__all__ = ( + 'FeatureSpec', +) diff --git a/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/multiclusteringress.py b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/multiclusteringress.py new file mode 100644 index 0000000..d07af4b --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/google/cloud/gkehub/multiclusteringress_v1/types/multiclusteringress.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.multiclusteringress.v1', + manifest={ + 'FeatureSpec', + }, +) + + +class FeatureSpec(proto.Message): + r"""**Multi-cluster Ingress**: The configuration for the + MultiClusterIngress feature. + + Attributes: + config_membership (str): + Fully-qualified Membership name which hosts the + MultiClusterIngress CRD. Example: + ``projects/foo-proj/locations/global/memberships/bar`` + """ + + config_membership: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/multiclusteringress/mypy.ini b/owl-bot-staging/v1/multiclusteringress/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/multiclusteringress/noxfile.py b/owl-bot-staging/v1/multiclusteringress/noxfile.py new file mode 100644 index 0000000..c3e2db9 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gkehub/multiclusteringress_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@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( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/multiclusteringress/scripts/fixup_multiclusteringress_v1_keywords.py b/owl-bot-staging/v1/multiclusteringress/scripts/fixup_multiclusteringress_v1_keywords.py new file mode 100644 index 0000000..73474fa --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/scripts/fixup_multiclusteringress_v1_keywords.py @@ -0,0 +1,175 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 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 multiclusteringressCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + } + + 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=multiclusteringressCallTransformer(), +): + """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 multiclusteringress 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/v1/multiclusteringress/setup.py b/owl-bot-staging/v1/multiclusteringress/setup.py new file mode 100644 index 0000000..4fab046 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-gkehub-multiclusteringress' + + +description = "Google Cloud Gkehub Multiclusteringress API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/gkehub/multiclusteringress/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +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.0, <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.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-gkehub-multiclusteringress" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.gkehub"] + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.10.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.11.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.12.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.12.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.7.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.7.txt new file mode 100644 index 0000000..6c44adf --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# 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.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.8.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.9.txt b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/multiclusteringress/tests/__init__.py b/owl-bot-staging/v1/multiclusteringress/tests/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/tests/unit/__init__.py b/owl-bot-staging/v1/multiclusteringress/tests/unit/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/multiclusteringress/tests/unit/gapic/multiclusteringress_v1/__init__.py b/owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/multiclusteringress_v1/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/multiclusteringress/tests/unit/gapic/multiclusteringress_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..50ca532 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gkehub_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@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( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_async.py new file mode 100644 index 0000000..bd1c06c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateFeature_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 gkehub_v1 + + +async def sample_create_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFeatureRequest( + ) + + # Make the request + operation = client.create_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_CreateFeature_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_sync.py new file mode 100644 index 0000000..04691a0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_feature_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateFeature_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 gkehub_v1 + + +def sample_create_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFeatureRequest( + ) + + # Make the request + operation = client.create_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_CreateFeature_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_async.py new file mode 100644 index 0000000..38b5356 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembership_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 gkehub_v1 + + +async def sample_create_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_CreateMembership_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_sync.py new file mode 100644 index 0000000..f7e3673 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembership_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 gkehub_v1 + + +def sample_create_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_CreateMembership_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_async.py new file mode 100644 index 0000000..a972300 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteFeature_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 gkehub_v1 + + +async def sample_delete_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFeatureRequest( + ) + + # Make the request + operation = client.delete_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_DeleteFeature_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_sync.py new file mode 100644 index 0000000..ee2d8ef --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_feature_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteFeature_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 gkehub_v1 + + +def sample_delete_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFeatureRequest( + ) + + # Make the request + operation = client.delete_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_DeleteFeature_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_async.py new file mode 100644 index 0000000..ade650e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembership_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 gkehub_v1 + + +async def sample_delete_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_DeleteMembership_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_sync.py new file mode 100644 index 0000000..c69fb0b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembership_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 gkehub_v1 + + +def sample_delete_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_DeleteMembership_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py new file mode 100644 index 0000000..df0e228 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateConnectManifest +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GenerateConnectManifest_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 gkehub_v1 + + +async def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GenerateConnectManifest_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py new file mode 100644 index 0000000..506d31b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateConnectManifest +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GenerateConnectManifest_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 gkehub_v1 + + +def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GenerateConnectManifest_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_async.py new file mode 100644 index 0000000..d5ef89f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetFeature_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 gkehub_v1 + + +async def sample_get_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFeatureRequest( + ) + + # Make the request + response = await client.get_feature(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GetFeature_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_sync.py new file mode 100644 index 0000000..db8d9cd --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_feature_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetFeature_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 gkehub_v1 + + +def sample_get_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFeatureRequest( + ) + + # Make the request + response = client.get_feature(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GetFeature_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_async.py new file mode 100644 index 0000000..4e5e157 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembership_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 gkehub_v1 + + +async def sample_get_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GetMembership_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_sync.py new file mode 100644 index 0000000..51fea8b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembership_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 gkehub_v1 + + +def sample_get_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_GetMembership_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_async.py new file mode 100644 index 0000000..ff27135 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListFeatures +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListFeatures_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 gkehub_v1 + + +async def sample_list_features(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFeaturesRequest( + ) + + # Make the request + page_result = client.list_features(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkehub_v1_generated_GkeHub_ListFeatures_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_sync.py new file mode 100644 index 0000000..6a5537d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_features_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListFeatures +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListFeatures_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 gkehub_v1 + + +def sample_list_features(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFeaturesRequest( + ) + + # Make the request + page_result = client.list_features(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkehub_v1_generated_GkeHub_ListFeatures_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_async.py new file mode 100644 index 0000000..78e235d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMemberships_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 gkehub_v1 + + +async def sample_list_memberships(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkehub_v1_generated_GkeHub_ListMemberships_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_sync.py new file mode 100644 index 0000000..9d5edd8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_list_memberships_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMemberships_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 gkehub_v1 + + +def sample_list_memberships(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkehub_v1_generated_GkeHub_ListMemberships_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_async.py new file mode 100644 index 0000000..3d933f7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateFeature_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 gkehub_v1 + + +async def sample_update_feature(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFeatureRequest( + ) + + # Make the request + operation = client.update_feature(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_UpdateFeature_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_sync.py new file mode 100644 index 0000000..c1db142 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_feature_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateFeature +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateFeature_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 gkehub_v1 + + +def sample_update_feature(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFeatureRequest( + ) + + # Make the request + operation = client.update_feature(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_UpdateFeature_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_async.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_async.py new file mode 100644 index 0000000..a15aac4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembership_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 gkehub_v1 + + +async def sample_update_membership(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_UpdateMembership_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_sync.py b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_sync.py new file mode 100644 index 0000000..d28946e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMembership +# 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-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembership_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 gkehub_v1 + + +def sample_update_membership(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1_generated_GkeHub_UpdateMembership_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json new file mode 100644 index 0000000..f5d7aaa --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json @@ -0,0 +1,1842 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.gkehub.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-gke-hub", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateFeatureRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "name": "feature_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_feature" + }, + "description": "Sample for CreateFeature", + "file": "gkehub_v1_generated_gke_hub_create_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateFeature_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": "gkehub_v1_generated_gke_hub_create_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateFeatureRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "name": "feature_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_feature" + }, + "description": "Sample for CreateFeature", + "file": "gkehub_v1_generated_gke_hub_create_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateFeature_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": "gkehub_v1_generated_gke_hub_create_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "membership_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_membership" + }, + "description": "Sample for CreateMembership", + "file": "gkehub_v1_generated_gke_hub_create_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "membership_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_membership" + }, + "description": "Sample for CreateMembership", + "file": "gkehub_v1_generated_gke_hub_create_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + }, + { + "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_feature" + }, + "description": "Sample for DeleteFeature", + "file": "gkehub_v1_generated_gke_hub_delete_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_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": "gkehub_v1_generated_gke_hub_delete_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + }, + { + "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_feature" + }, + "description": "Sample for DeleteFeature", + "file": "gkehub_v1_generated_gke_hub_delete_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_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": "gkehub_v1_generated_gke_hub_delete_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + }, + { + "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_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1_generated_gke_hub_delete_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_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": "gkehub_v1_generated_gke_hub_delete_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + }, + { + "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_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1_generated_gke_hub_delete_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_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": "gkehub_v1_generated_gke_hub_delete_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_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": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_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": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + }, + { + "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.gkehub_v1.types.Feature", + "shortName": "get_feature" + }, + "description": "Sample for GetFeature", + "file": "gkehub_v1_generated_gke_hub_get_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_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": "gkehub_v1_generated_gke_hub_get_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + }, + { + "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.gkehub_v1.types.Feature", + "shortName": "get_feature" + }, + "description": "Sample for GetFeature", + "file": "gkehub_v1_generated_gke_hub_get_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_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": "gkehub_v1_generated_gke_hub_get_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + }, + { + "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.gkehub_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1_generated_gke_hub_get_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_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": "gkehub_v1_generated_gke_hub_get_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + }, + { + "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.gkehub_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1_generated_gke_hub_get_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_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": "gkehub_v1_generated_gke_hub_get_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_features", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFeatures" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + }, + { + "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.gkehub_v1.services.gke_hub.pagers.ListFeaturesAsyncPager", + "shortName": "list_features" + }, + "description": "Sample for ListFeatures", + "file": "gkehub_v1_generated_gke_hub_list_features_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_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": "gkehub_v1_generated_gke_hub_list_features_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_features", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFeatures" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + }, + { + "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.gkehub_v1.services.gke_hub.pagers.ListFeaturesPager", + "shortName": "list_features" + }, + "description": "Sample for ListFeatures", + "file": "gkehub_v1_generated_gke_hub_list_features_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_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": "gkehub_v1_generated_gke_hub_list_features_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + }, + { + "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.gkehub_v1.services.gke_hub.pagers.ListMembershipsAsyncPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1_generated_gke_hub_list_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_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": "gkehub_v1_generated_gke_hub_list_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + }, + { + "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.gkehub_v1.services.gke_hub.pagers.ListMembershipsPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1_generated_gke_hub_list_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_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": "gkehub_v1_generated_gke_hub_list_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "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_feature" + }, + "description": "Sample for UpdateFeature", + "file": "gkehub_v1_generated_gke_hub_update_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_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": "gkehub_v1_generated_gke_hub_update_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "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_feature" + }, + "description": "Sample for UpdateFeature", + "file": "gkehub_v1_generated_gke_hub_update_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_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": "gkehub_v1_generated_gke_hub_update_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "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_membership" + }, + "description": "Sample for UpdateMembership", + "file": "gkehub_v1_generated_gke_hub_update_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_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": "gkehub_v1_generated_gke_hub_update_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "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_membership" + }, + "description": "Sample for UpdateMembership", + "file": "gkehub_v1_generated_gke_hub_update_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_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": "gkehub_v1_generated_gke_hub_update_membership_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_gkehub_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_gkehub_v1_keywords.py new file mode 100644 index 0000000..937b241 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_gkehub_v1_keywords.py @@ -0,0 +1,186 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 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 gkehubCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_feature': ('parent', 'feature_id', 'resource', 'request_id', ), + 'create_membership': ('parent', 'membership_id', 'resource', 'request_id', ), + 'delete_feature': ('name', 'force', 'request_id', ), + 'delete_membership': ('name', 'request_id', 'force', ), + 'generate_connect_manifest': ('name', 'namespace', 'proxy', 'version', 'is_upgrade', 'registry', 'image_pull_secret_content', ), + 'get_feature': ('name', ), + 'get_membership': ('name', ), + 'list_features': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_memberships': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_feature': ('name', 'update_mask', 'resource', 'request_id', ), + 'update_membership': ('name', 'update_mask', 'resource', 'request_id', ), + } + + 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=gkehubCallTransformer(), +): + """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 gkehub 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/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..0a82b08 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-gke-hub' + + +description = "Google Cloud Gke Hub API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/gkehub/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +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.0, <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.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-gke-hub" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 0000000..6c44adf --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# 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.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 0000000..ed7f9ae --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/tests/unit/gapic/gkehub_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1/tests/unit/gapic/gkehub_v1/test_gke_hub.py b/owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/test_gke_hub.py new file mode 100644 index 0000000..41a87ca --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/gkehub_v1/test_gke_hub.py @@ -0,0 +1,6795 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 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.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.gkehub.configmanagement.v1 import configmanagement_pb2 # type: ignore +from google.cloud.gkehub.multiclusteringress.v1 import multiclusteringress_pb2 # type: ignore +from google.cloud.gkehub_v1.services.gke_hub import GkeHubAsyncClient +from google.cloud.gkehub_v1.services.gke_hub import GkeHubClient +from google.cloud.gkehub_v1.services.gke_hub import pagers +from google.cloud.gkehub_v1.services.gke_hub import transports +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import membership +from google.cloud.gkehub_v1.types import service +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 + + +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 GkeHubClient._get_default_mtls_endpoint(None) is None + assert GkeHubClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GkeHubClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GkeHubClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GkeHubClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GkeHubClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (GkeHubClient, "grpc"), + (GkeHubAsyncClient, "grpc_asyncio"), + (GkeHubClient, "rest"), +]) +def test_gke_hub_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 == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkehub.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.GkeHubGrpcTransport, "grpc"), + (transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GkeHubRestTransport, "rest"), +]) +def test_gke_hub_client_service_account_always_use_jwt(transport_class, transport_name): + 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", [ + (GkeHubClient, "grpc"), + (GkeHubAsyncClient, "grpc_asyncio"), + (GkeHubClient, "rest"), +]) +def test_gke_hub_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 == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkehub.googleapis.com' + ) + + +def test_gke_hub_client_get_transport_class(): + transport = GkeHubClient.get_transport_class() + available_transports = [ + transports.GkeHubGrpcTransport, + transports.GkeHubRestTransport, + ] + assert transport in available_transports + + transport = GkeHubClient.get_transport_class("grpc") + assert transport == transports.GkeHubGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc"), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubClient, transports.GkeHubRestTransport, "rest"), +]) +@mock.patch.object(GkeHubClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubClient)) +@mock.patch.object(GkeHubAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubAsyncClient)) +def test_gke_hub_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(GkeHubClient, '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(GkeHubClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc", "true"), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc", "false"), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (GkeHubClient, transports.GkeHubRestTransport, "rest", "true"), + (GkeHubClient, transports.GkeHubRestTransport, "rest", "false"), +]) +@mock.patch.object(GkeHubClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubClient)) +@mock.patch.object(GkeHubAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_gke_hub_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + GkeHubClient, GkeHubAsyncClient +]) +@mock.patch.object(GkeHubClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubClient)) +@mock.patch.object(GkeHubAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubAsyncClient)) +def test_gke_hub_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc"), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubClient, transports.GkeHubRestTransport, "rest"), +]) +def test_gke_hub_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc", grpc_helpers), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (GkeHubClient, transports.GkeHubRestTransport, "rest", None), +]) +def test_gke_hub_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_gke_hub_client_client_options_from_dict(): + with mock.patch('google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GkeHubClient( + 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", [ + (GkeHubClient, transports.GkeHubGrpcTransport, "grpc", grpc_helpers), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_gke_hub_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "gkehub.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="gkehub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListMembershipsRequest, + dict, +]) +def test_list_memberships(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_memberships_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 = GkeHubClient( + 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_memberships), + '__call__') as call: + client.list_memberships() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListMembershipsRequest() + +@pytest.mark.asyncio +async def test_list_memberships_async(transport: str = 'grpc_asyncio', request_type=service.ListMembershipsRequest): + client = GkeHubAsyncClient( + 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListMembershipsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_memberships_async_from_dict(): + await test_list_memberships_async(request_type=dict) + + +def test_list_memberships_field_headers(): + client = GkeHubClient( + 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 = service.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = service.ListMembershipsResponse() + client.list_memberships(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_memberships_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListMembershipsResponse()) + await client.list_memberships(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_memberships_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_memberships( + 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_memberships_flattened_error(): + client = GkeHubClient( + 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_memberships( + service.ListMembershipsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_memberships_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListMembershipsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_memberships( + 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_memberships_flattened_error_async(): + client = GkeHubAsyncClient( + 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_memberships( + service.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_pager(transport_name: str = "grpc"): + client = GkeHubClient( + 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_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + service.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_memberships(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) +def test_list_memberships_pages(transport_name: str = "grpc"): + client = GkeHubClient( + 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_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + service.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + pages = list(client.list_memberships(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_memberships_async_pager(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + service.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_memberships(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, membership.Membership) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_memberships_async_pages(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + service.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + 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_memberships(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", [ + service.ListFeaturesRequest, + dict, +]) +def test_list_features(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_features), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFeaturesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_features(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListFeaturesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFeaturesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_features_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 = GkeHubClient( + 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_features), + '__call__') as call: + client.list_features() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListFeaturesRequest() + +@pytest.mark.asyncio +async def test_list_features_async(transport: str = 'grpc_asyncio', request_type=service.ListFeaturesRequest): + client = GkeHubAsyncClient( + 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_features), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListFeaturesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_features(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListFeaturesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFeaturesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_features_async_from_dict(): + await test_list_features_async(request_type=dict) + + +def test_list_features_field_headers(): + client = GkeHubClient( + 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 = service.ListFeaturesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__') as call: + call.return_value = service.ListFeaturesResponse() + client.list_features(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_features_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.ListFeaturesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListFeaturesResponse()) + await client.list_features(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_features_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFeaturesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_features( + 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_features_flattened_error(): + client = GkeHubClient( + 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_features( + service.ListFeaturesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_features_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFeaturesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListFeaturesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_features( + 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_features_flattened_error_async(): + client = GkeHubAsyncClient( + 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_features( + service.ListFeaturesRequest(), + parent='parent_value', + ) + + +def test_list_features_pager(transport_name: str = "grpc"): + client = GkeHubClient( + 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_features), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token='abc', + ), + service.ListFeaturesResponse( + resources=[], + next_page_token='def', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token='ghi', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_features(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, feature.Feature) + for i in results) +def test_list_features_pages(transport_name: str = "grpc"): + client = GkeHubClient( + 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_features), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token='abc', + ), + service.ListFeaturesResponse( + resources=[], + next_page_token='def', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token='ghi', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, + ) + pages = list(client.list_features(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_features_async_pager(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token='abc', + ), + service.ListFeaturesResponse( + resources=[], + next_page_token='def', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token='ghi', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_features(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, feature.Feature) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_features_async_pages(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token='abc', + ), + service.ListFeaturesResponse( + resources=[], + next_page_token='def', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token='ghi', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + 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_features(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", [ + service.GetMembershipRequest, + dict, +]) +def test_get_membership(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + ) + response = client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + + +def test_get_membership_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 = GkeHubClient( + 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_membership), + '__call__') as call: + client.get_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipRequest() + +@pytest.mark.asyncio +async def test_get_membership_async(transport: str = 'grpc_asyncio', request_type=service.GetMembershipRequest): + client = GkeHubAsyncClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + )) + response = await client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + + +@pytest.mark.asyncio +async def test_get_membership_async_from_dict(): + await test_get_membership_async(request_type=dict) + + +def test_get_membership_field_headers(): + client = GkeHubClient( + 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 = service.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = membership.Membership() + client.get_membership(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_membership_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + await client.get_membership(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_membership_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership( + 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_membership_flattened_error(): + client = GkeHubClient( + 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_membership( + service.GetMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_membership_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership( + 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_membership_flattened_error_async(): + client = GkeHubAsyncClient( + 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_membership( + service.GetMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetFeatureRequest, + dict, +]) +def test_get_feature(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = feature.Feature( + name='name_value', + ) + response = client.get_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, feature.Feature) + assert response.name == 'name_value' + + +def test_get_feature_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 = GkeHubClient( + 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_feature), + '__call__') as call: + client.get_feature() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetFeatureRequest() + +@pytest.mark.asyncio +async def test_get_feature_async(transport: str = 'grpc_asyncio', request_type=service.GetFeatureRequest): + client = GkeHubAsyncClient( + 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_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature( + name='name_value', + )) + response = await client.get_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, feature.Feature) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_feature_async_from_dict(): + await test_get_feature_async(request_type=dict) + + +def test_get_feature_field_headers(): + client = GkeHubClient( + 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 = service.GetFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feature), + '__call__') as call: + call.return_value = feature.Feature() + client.get_feature(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_feature_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.GetFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feature), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) + await client.get_feature(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_feature_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = feature.Feature() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_feature( + 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_feature_flattened_error(): + client = GkeHubClient( + 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_feature( + service.GetFeatureRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_feature_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = feature.Feature() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_feature( + 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_feature_flattened_error_async(): + client = GkeHubAsyncClient( + 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_feature( + service.GetFeatureRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateMembershipRequest, + dict, +]) +def test_create_membership(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_membership_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 = GkeHubClient( + 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_membership), + '__call__') as call: + client.create_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateMembershipRequest() + +@pytest.mark.asyncio +async def test_create_membership_async(transport: str = 'grpc_asyncio', request_type=service.CreateMembershipRequest): + client = GkeHubAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_membership_async_from_dict(): + await test_create_membership_async(request_type=dict) + + +def test_create_membership_field_headers(): + client = GkeHubClient( + 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 = service.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_membership(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_membership_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_membership(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_membership_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__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_membership( + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_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].resource + mock_val = membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))) + assert arg == mock_val + arg = args[0].membership_id + mock_val = 'membership_id_value' + assert arg == mock_val + + +def test_create_membership_flattened_error(): + client = GkeHubClient( + 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_membership( + service.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_id_value', + ) + +@pytest.mark.asyncio +async def test_create_membership_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__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_membership( + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_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].resource + mock_val = membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))) + assert arg == mock_val + arg = args[0].membership_id + mock_val = 'membership_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_membership_flattened_error_async(): + client = GkeHubAsyncClient( + 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_membership( + service.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateFeatureRequest, + dict, +]) +def test_create_feature(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_feature_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 = GkeHubClient( + 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_feature), + '__call__') as call: + client.create_feature() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateFeatureRequest() + +@pytest.mark.asyncio +async def test_create_feature_async(transport: str = 'grpc_asyncio', request_type=service.CreateFeatureRequest): + client = GkeHubAsyncClient( + 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_feature), + '__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_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_feature_async_from_dict(): + await test_create_feature_async(request_type=dict) + + +def test_create_feature_field_headers(): + client = GkeHubClient( + 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 = service.CreateFeatureRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feature), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_feature(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_feature_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.CreateFeatureRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feature), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_feature(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_feature_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feature), + '__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_feature( + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_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].resource + mock_val = feature.Feature(name='name_value') + assert arg == mock_val + arg = args[0].feature_id + mock_val = 'feature_id_value' + assert arg == mock_val + + +def test_create_feature_flattened_error(): + client = GkeHubClient( + 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_feature( + service.CreateFeatureRequest(), + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_id_value', + ) + +@pytest.mark.asyncio +async def test_create_feature_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feature), + '__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_feature( + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_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].resource + mock_val = feature.Feature(name='name_value') + assert arg == mock_val + arg = args[0].feature_id + mock_val = 'feature_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_feature_flattened_error_async(): + client = GkeHubAsyncClient( + 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_feature( + service.CreateFeatureRequest(), + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteMembershipRequest, + dict, +]) +def test_delete_membership(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_membership_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 = GkeHubClient( + 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_membership), + '__call__') as call: + client.delete_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteMembershipRequest() + +@pytest.mark.asyncio +async def test_delete_membership_async(transport: str = 'grpc_asyncio', request_type=service.DeleteMembershipRequest): + client = GkeHubAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_membership_async_from_dict(): + await test_delete_membership_async(request_type=dict) + + +def test_delete_membership_field_headers(): + client = GkeHubClient( + 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 = service.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_membership(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_membership_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_membership(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_membership_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__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_membership( + 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_membership_flattened_error(): + client = GkeHubClient( + 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_membership( + service.DeleteMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_membership_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__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_membership( + 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_membership_flattened_error_async(): + client = GkeHubAsyncClient( + 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_membership( + service.DeleteMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteFeatureRequest, + dict, +]) +def test_delete_feature(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_feature_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 = GkeHubClient( + 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_feature), + '__call__') as call: + client.delete_feature() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteFeatureRequest() + +@pytest.mark.asyncio +async def test_delete_feature_async(transport: str = 'grpc_asyncio', request_type=service.DeleteFeatureRequest): + client = GkeHubAsyncClient( + 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_feature), + '__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_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_feature_async_from_dict(): + await test_delete_feature_async(request_type=dict) + + +def test_delete_feature_field_headers(): + client = GkeHubClient( + 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 = service.DeleteFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feature), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_feature(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_feature_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.DeleteFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feature), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_feature(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_feature_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feature), + '__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_feature( + 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_feature_flattened_error(): + client = GkeHubClient( + 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_feature( + service.DeleteFeatureRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_feature_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feature), + '__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_feature( + 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_feature_flattened_error_async(): + client = GkeHubAsyncClient( + 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_feature( + service.DeleteFeatureRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateMembershipRequest, + dict, +]) +def test_update_membership(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_membership_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 = GkeHubClient( + 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_membership), + '__call__') as call: + client.update_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateMembershipRequest() + +@pytest.mark.asyncio +async def test_update_membership_async(transport: str = 'grpc_asyncio', request_type=service.UpdateMembershipRequest): + client = GkeHubAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_membership_async_from_dict(): + await test_update_membership_async(request_type=dict) + + +def test_update_membership_field_headers(): + client = GkeHubClient( + 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 = service.UpdateMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_membership(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_update_membership_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.UpdateMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_membership(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_update_membership_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__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_membership( + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # 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].resource + mock_val = membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_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_membership_flattened_error(): + client = GkeHubClient( + 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_membership( + service.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_membership_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__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_membership( + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # 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].resource + mock_val = membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_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_membership_flattened_error_async(): + client = GkeHubAsyncClient( + 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_membership( + service.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateFeatureRequest, + dict, +]) +def test_update_feature(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_feature), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_feature_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 = GkeHubClient( + 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_feature), + '__call__') as call: + client.update_feature() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateFeatureRequest() + +@pytest.mark.asyncio +async def test_update_feature_async(transport: str = 'grpc_asyncio', request_type=service.UpdateFeatureRequest): + client = GkeHubAsyncClient( + 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_feature), + '__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_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateFeatureRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_feature_async_from_dict(): + await test_update_feature_async(request_type=dict) + + +def test_update_feature_field_headers(): + client = GkeHubClient( + 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 = service.UpdateFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feature), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_feature(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_update_feature_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.UpdateFeatureRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feature), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_feature(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_update_feature_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feature), + '__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_feature( + name='name_value', + resource=feature.Feature(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(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_feature_flattened_error(): + client = GkeHubClient( + 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_feature( + service.UpdateFeatureRequest(), + name='name_value', + resource=feature.Feature(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_feature_flattened_async(): + client = GkeHubAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feature), + '__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_feature( + name='name_value', + resource=feature.Feature(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(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_feature_flattened_error_async(): + client = GkeHubAsyncClient( + 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_feature( + service.UpdateFeatureRequest(), + name='name_value', + resource=feature.Feature(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.GenerateConnectManifestRequest, + dict, +]) +def test_generate_connect_manifest(request_type, transport: str = 'grpc'): + client = GkeHubClient( + 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_connect_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateConnectManifestResponse( + ) + response = client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateConnectManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_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 = GkeHubClient( + 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_connect_manifest), + '__call__') as call: + client.generate_connect_manifest() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateConnectManifestRequest() + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async(transport: str = 'grpc_asyncio', request_type=service.GenerateConnectManifestRequest): + client = GkeHubAsyncClient( + 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_connect_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateConnectManifestResponse( + )) + response = await client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateConnectManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async_from_dict(): + await test_generate_connect_manifest_async(request_type=dict) + + +def test_generate_connect_manifest_field_headers(): + client = GkeHubClient( + 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 = service.GenerateConnectManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), + '__call__') as call: + call.return_value = service.GenerateConnectManifestResponse() + client.generate_connect_manifest(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_connect_manifest_field_headers_async(): + client = GkeHubAsyncClient( + 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 = service.GenerateConnectManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateConnectManifestResponse()) + await client.generate_connect_manifest(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", [ + service.ListMembershipsRequest, + dict, +]) +def test_list_memberships_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListMembershipsResponse.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_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_memberships_rest_required_fields(request_type=service.ListMembershipsRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipsResponse.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_memberships(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_list_memberships") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_list_memberships") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListMembershipsRequest.pb(service.ListMembershipsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListMembershipsResponse.to_json(service.ListMembershipsResponse()) + + request = service.ListMembershipsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListMembershipsResponse() + + client.list_memberships(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request(transport: str = 'rest', request_type=service.ListMembershipsRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse() + + # 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 = service.ListMembershipsResponse.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_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/memberships" % client.transport._host, args[1]) + + +def test_list_memberships_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memberships( + service.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_rest_pager(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + service.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListMembershipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + service.ListFeaturesRequest, + dict, +]) +def test_list_features_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFeaturesResponse( + next_page_token='next_page_token_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 = service.ListFeaturesResponse.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_features(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFeaturesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_features_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_list_features") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_list_features") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListFeaturesRequest.pb(service.ListFeaturesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListFeaturesResponse.to_json(service.ListFeaturesResponse()) + + request = service.ListFeaturesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListFeaturesResponse() + + client.list_features(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_features_rest_bad_request(transport: str = 'rest', request_type=service.ListFeaturesRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_features(request) + + +def test_list_features_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFeaturesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListFeaturesResponse.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_features(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, args[1]) + + +def test_list_features_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_features( + service.ListFeaturesRequest(), + parent='parent_value', + ) + + +def test_list_features_rest_pager(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token='abc', + ), + service.ListFeaturesResponse( + resources=[], + next_page_token='def', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token='ghi', + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListFeaturesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_features(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, feature.Feature) + for i in results) + + pages = list(client.list_features(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + service.GetMembershipRequest, + dict, +]) +def test_get_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + + +def test_get_membership_rest_required_fields(request_type=service.GetMembershipRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_get_membership") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_get_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetMembershipRequest.pb(service.GetMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json(membership.Membership()) + + request = service.GetMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.get_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_membership_rest_bad_request(transport: str = 'rest', request_type=service.GetMembershipRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_membership(request) + + +def test_get_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_get_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_membership( + service.GetMembershipRequest(), + name='name_value', + ) + + +def test_get_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetFeatureRequest, + dict, +]) +def test_get_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = feature.Feature( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = feature.Feature.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_feature(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, feature.Feature) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_get_feature") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_get_feature") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetFeatureRequest.pb(service.GetFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = feature.Feature.to_json(feature.Feature()) + + request = service.GetFeatureRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = feature.Feature() + + client.get_feature(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_feature_rest_bad_request(transport: str = 'rest', request_type=service.GetFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_feature(request) + + +def test_get_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = feature.Feature() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/features/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = feature.Feature.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_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, args[1]) + + +def test_get_feature_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_feature( + service.GetFeatureRequest(), + name='name_value', + ) + + +def test_get_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateMembershipRequest, + dict, +]) +def test_create_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["resource"] = {'endpoint': {'gke_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'kubernetes_metadata': {'kubernetes_api_server_version': 'kubernetes_api_server_version_value', 'node_provider_id': 'node_provider_id_value', 'node_count': 1070, 'vcpu_count': 1094, 'memory_mb': 967, 'update_time': {'seconds': 751, 'nanos': 543}}, 'kubernetes_resource': {'membership_cr_manifest': 'membership_cr_manifest_value', 'membership_resources': [{'manifest': 'manifest_value', 'cluster_scoped': True}], 'connect_resources': {}, 'resource_options': {'connect_version': 'connect_version_value', 'v1beta1_crd': True, 'k8s_version': 'k8s_version_value'}}, 'google_managed': True}, 'name': 'name_value', 'labels': {}, 'description': 'description_value', 'state': {'code': 1}, 'create_time': {}, 'update_time': {}, 'delete_time': {}, 'external_id': 'external_id_value', 'last_connection_time': {}, 'unique_id': 'unique_id_value', 'authority': {'issuer': 'issuer_value', 'workload_identity_pool': 'workload_identity_pool_value', 'identity_provider': 'identity_provider_value', 'oidc_jwks': b'oidc_jwks_blob'}, 'monitoring_config': {'project_id': 'project_id_value', 'location': 'location_value', 'cluster': 'cluster_value', 'kubernetes_metrics_prefix': 'kubernetes_metrics_prefix_value', 'cluster_hash': 'cluster_hash_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 = service.CreateMembershipRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_membership_rest_required_fields(request_type=service.CreateMembershipRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "membershipId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == request_init["membership_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["membershipId"] = 'membership_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("membership_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == 'membership_id_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_membership(request) + + expected_params = [ + ( + "membershipId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("membershipId", "requestId", )) & set(("parent", "membershipId", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_create_membership") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_create_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateMembershipRequest.pb(service.CreateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.CreateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request(transport: str = 'rest', request_type=service.CreateMembershipRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_membership(request) + + +def test_create_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/memberships" % client.transport._host, args[1]) + + +def test_create_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_membership( + service.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + membership_id='membership_id_value', + ) + + +def test_create_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateFeatureRequest, + dict, +]) +def test_create_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["resource"] = {'name': 'name_value', 'labels': {}, 'resource_state': {'state': 1}, 'spec': {'multiclusteringress': {'config_membership': 'config_membership_value'}}, 'membership_specs': {}, 'state': {'state': {'code': 1, 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}}}, 'membership_states': {}, 'create_time': {}, 'update_time': {}, 'delete_time': {}} + # 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 = service.CreateFeatureRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_create_feature") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_create_feature") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateFeatureRequest.pb(service.CreateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.CreateFeatureRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_feature(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_feature_rest_bad_request(transport: str = 'rest', request_type=service.CreateFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_feature(request) + + +def test_create_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, args[1]) + + +def test_create_feature_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_feature( + service.CreateFeatureRequest(), + parent='parent_value', + resource=feature.Feature(name='name_value'), + feature_id='feature_id_value', + ) + + +def test_create_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteMembershipRequest, + dict, +]) +def test_delete_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_membership_rest_required_fields(request_type=service.DeleteMembershipRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_delete_membership") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_delete_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteMembershipRequest.pb(service.DeleteMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.DeleteMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request(transport: str = 'rest', request_type=service.DeleteMembershipRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_delete_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + service.DeleteMembershipRequest(), + name='name_value', + ) + + +def test_delete_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.DeleteFeatureRequest, + dict, +]) +def test_delete_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_delete_feature") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_delete_feature") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteFeatureRequest.pb(service.DeleteFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.DeleteFeatureRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_feature(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_feature_rest_bad_request(transport: str = 'rest', request_type=service.DeleteFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_feature(request) + + +def test_delete_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/features/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, args[1]) + + +def test_delete_feature_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_feature( + service.DeleteFeatureRequest(), + name='name_value', + ) + + +def test_delete_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateMembershipRequest, + dict, +]) +def test_update_membership_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request_init["resource"] = {'endpoint': {'gke_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'kubernetes_metadata': {'kubernetes_api_server_version': 'kubernetes_api_server_version_value', 'node_provider_id': 'node_provider_id_value', 'node_count': 1070, 'vcpu_count': 1094, 'memory_mb': 967, 'update_time': {'seconds': 751, 'nanos': 543}}, 'kubernetes_resource': {'membership_cr_manifest': 'membership_cr_manifest_value', 'membership_resources': [{'manifest': 'manifest_value', 'cluster_scoped': True}], 'connect_resources': {}, 'resource_options': {'connect_version': 'connect_version_value', 'v1beta1_crd': True, 'k8s_version': 'k8s_version_value'}}, 'google_managed': True}, 'name': 'name_value', 'labels': {}, 'description': 'description_value', 'state': {'code': 1}, 'create_time': {}, 'update_time': {}, 'delete_time': {}, 'external_id': 'external_id_value', 'last_connection_time': {}, 'unique_id': 'unique_id_value', 'authority': {'issuer': 'issuer_value', 'workload_identity_pool': 'workload_identity_pool_value', 'identity_provider': 'identity_provider_value', 'oidc_jwks': b'oidc_jwks_blob'}, 'monitoring_config': {'project_id': 'project_id_value', 'location': 'location_value', 'cluster': 'cluster_value', 'kubernetes_metrics_prefix': 'kubernetes_metrics_prefix_value', 'cluster_hash': 'cluster_hash_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 = service.UpdateMembershipRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_membership_rest_required_fields(request_type=service.UpdateMembershipRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("name", "updateMask", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_update_membership") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_update_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateMembershipRequest.pb(service.UpdateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.UpdateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_membership_rest_bad_request(transport: str = 'rest', request_type=service.UpdateMembershipRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_membership(request) + + +def test_update_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_update_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership( + service.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(endpoint=membership.MembershipEndpoint(gke_cluster=membership.GkeCluster(resource_link='resource_link_value'))), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_membership_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateFeatureRequest, + dict, +]) +def test_update_feature_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request_init["resource"] = {'name': 'name_value', 'labels': {}, 'resource_state': {'state': 1}, 'spec': {'multiclusteringress': {'config_membership': 'config_membership_value'}}, 'membership_specs': {}, 'state': {'state': {'code': 1, 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}}}, 'membership_states': {}, 'create_time': {}, 'update_time': {}, 'delete_time': {}} + # 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 = service.UpdateFeatureRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_feature(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_update_feature") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_update_feature") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateFeatureRequest.pb(service.UpdateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = service.UpdateFeatureRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_feature(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_feature_rest_bad_request(transport: str = 'rest', request_type=service.UpdateFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/features/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_feature(request) + + +def test_update_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/features/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + resource=feature.Feature(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, args[1]) + + +def test_update_feature_rest_flattened_error(transport: str = 'rest'): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_feature( + service.UpdateFeatureRequest(), + name='name_value', + resource=feature.Feature(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_feature_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + service.GenerateConnectManifestRequest, + dict, +]) +def test_generate_connect_manifest_rest(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateConnectManifestResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.GenerateConnectManifestResponse.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_connect_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_rest_required_fields(request_type=service.GenerateConnectManifestRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_connect_manifest._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_connect_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("image_pull_secret_content", "is_upgrade", "namespace", "proxy", "registry", "version", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateConnectManifestResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.GenerateConnectManifestResponse.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_connect_manifest(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_connect_manifest_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) + assert set(unset_fields) == (set(("imagePullSecretContent", "isUpgrade", "namespace", "proxy", "registry", "version", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_connect_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubRestInterceptor, "post_generate_connect_manifest") as post, \ + mock.patch.object(transports.GkeHubRestInterceptor, "pre_generate_connect_manifest") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateConnectManifestRequest.pb(service.GenerateConnectManifestRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.GenerateConnectManifestResponse.to_json(service.GenerateConnectManifestResponse()) + + request = service.GenerateConnectManifestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateConnectManifestResponse() + + client.generate_connect_manifest(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_connect_manifest_rest_bad_request(transport: str = 'rest', request_type=service.GenerateConnectManifestRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_connect_manifest(request) + + +def test_generate_connect_manifest_rest_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GkeHubClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GkeHubGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GkeHubGrpcTransport, + transports.GkeHubGrpcAsyncIOTransport, + transports.GkeHubRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = GkeHubClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GkeHubGrpcTransport, + ) + +def test_gke_hub_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GkeHubTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_gke_hub_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GkeHubTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_memberships', + 'list_features', + 'get_membership', + 'get_feature', + 'create_membership', + 'create_feature', + 'delete_membership', + 'delete_feature', + 'update_membership', + 'update_feature', + 'generate_connect_manifest', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_gke_hub_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_gke_hub_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.gkehub_v1.services.gke_hub.transports.GkeHubTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubTransport() + adc.assert_called_once() + + +def test_gke_hub_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) + GkeHubClient() + 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.GkeHubGrpcTransport, + transports.GkeHubGrpcAsyncIOTransport, + ], +) +def test_gke_hub_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.GkeHubGrpcTransport, + transports.GkeHubGrpcAsyncIOTransport, + transports.GkeHubRestTransport, + ], +) +def test_gke_hub_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.GkeHubGrpcTransport, grpc_helpers), + (transports.GkeHubGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_gke_hub_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "gkehub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="gkehub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.GkeHubGrpcTransport, transports.GkeHubGrpcAsyncIOTransport]) +def test_gke_hub_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_gke_hub_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.GkeHubRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_gke_hub_rest_lro_client(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_gke_hub_host_no_port(transport_name): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkehub.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkehub.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_gke_hub_host_with_port(transport_name): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkehub.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkehub.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkehub.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_gke_hub_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GkeHubClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GkeHubClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.list_features._session + session2 = client2.transport.list_features._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.get_feature._session + session2 = client2.transport.get_feature._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.create_feature._session + session2 = client2.transport.create_feature._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.delete_feature._session + session2 = client2.transport.delete_feature._session + assert session1 != session2 + session1 = client1.transport.update_membership._session + session2 = client2.transport.update_membership._session + assert session1 != session2 + session1 = client1.transport.update_feature._session + session2 = client2.transport.update_feature._session + assert session1 != session2 + session1 = client1.transport.generate_connect_manifest._session + session2 = client2.transport.generate_connect_manifest._session + assert session1 != session2 +def test_gke_hub_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_gke_hub_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubGrpcAsyncIOTransport( + 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.GkeHubGrpcTransport, transports.GkeHubGrpcAsyncIOTransport]) +def test_gke_hub_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.GkeHubGrpcTransport, transports.GkeHubGrpcAsyncIOTransport]) +def test_gke_hub_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_gke_hub_grpc_lro_client(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_gke_hub_grpc_lro_async_client(): + client = GkeHubAsyncClient( + 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_feature_path(): + project = "squid" + location = "clam" + feature = "whelk" + expected = "projects/{project}/locations/{location}/features/{feature}".format(project=project, location=location, feature=feature, ) + actual = GkeHubClient.feature_path(project, location, feature) + assert expected == actual + + +def test_parse_feature_path(): + expected = { + "project": "octopus", + "location": "oyster", + "feature": "nudibranch", + } + path = GkeHubClient.feature_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_feature_path(path) + assert expected == actual + +def test_membership_path(): + project = "cuttlefish" + location = "mussel" + membership = "winkle" + expected = "projects/{project}/locations/{location}/memberships/{membership}".format(project=project, location=location, membership=membership, ) + actual = GkeHubClient.membership_path(project, location, membership) + assert expected == actual + + +def test_parse_membership_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "membership": "abalone", + } + path = GkeHubClient.membership_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_membership_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GkeHubClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = GkeHubClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = GkeHubClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = GkeHubClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GkeHubClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = GkeHubClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = GkeHubClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = GkeHubClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.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 = GkeHubClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = GkeHubClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.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.GkeHubTransport, '_prep_wrapped_messages') as prep: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GkeHubTransport, '_prep_wrapped_messages') as prep: + transport_class = GkeHubClient.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 = GkeHubAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = GkeHubClient( + 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 = GkeHubClient( + 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", [ + (GkeHubClient, transports.GkeHubGrpcTransport), + (GkeHubAsyncClient, transports.GkeHubGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 0000000..2653a96 --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/gkehub/__init__.py + google/cloud/gkehub/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/v1beta1/.flake8 b/owl-bot-staging/v1beta1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1beta1/.flake8 @@ -0,0 +1,33 @@ +# -*- 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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 0000000..5a63cc9 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/gkehub *.py +recursive-include google/cloud/gkehub_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 0000000..00b883a --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Gkehub 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 Gkehub 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/v1beta1/docs/_static/custom.css b/owl-bot-staging/v1beta1/docs/_static/custom.css new file mode 100644 index 0000000..06423be --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 0000000..121febc --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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-gke-hub 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-gke-hub" +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-gke-hub-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-gke-hub.tex", + u"google-cloud-gke-hub 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-gke-hub", + u"Google Cloud Gkehub 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-gke-hub", + u"google-cloud-gke-hub Documentation", + author, + "google-cloud-gke-hub", + "GAPIC library for Google Cloud Gkehub 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/v1beta1/docs/gkehub_v1beta1/gke_hub_membership_service.rst b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/gke_hub_membership_service.rst new file mode 100644 index 0000000..d234533 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/gke_hub_membership_service.rst @@ -0,0 +1,10 @@ +GkeHubMembershipService +----------------------------------------- + +.. automodule:: google.cloud.gkehub_v1beta1.services.gke_hub_membership_service + :members: + :inherited-members: + +.. automodule:: google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/services_.rst b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/services_.rst new file mode 100644 index 0000000..5ebd7a6 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Gkehub v1beta1 API +============================================ +.. toctree:: + :maxdepth: 2 + + gke_hub_membership_service diff --git a/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/types_.rst b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/types_.rst new file mode 100644 index 0000000..079f4fa --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/gkehub_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gkehub v1beta1 API +========================================= + +.. automodule:: google.cloud.gkehub_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 0000000..c840d89 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + gkehub_v1beta1/services + gkehub_v1beta1/types diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub/__init__.py new file mode 100644 index 0000000..13e616e --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.client import GkeHubMembershipServiceClient +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.async_client import GkeHubMembershipServiceAsyncClient + +from google.cloud.gkehub_v1beta1.types.membership import ApplianceCluster +from google.cloud.gkehub_v1beta1.types.membership import Authority +from google.cloud.gkehub_v1beta1.types.membership import ConnectAgent +from google.cloud.gkehub_v1beta1.types.membership import ConnectAgentResource +from google.cloud.gkehub_v1beta1.types.membership import CreateMembershipRequest +from google.cloud.gkehub_v1beta1.types.membership import DeleteMembershipRequest +from google.cloud.gkehub_v1beta1.types.membership import EdgeCluster +from google.cloud.gkehub_v1beta1.types.membership import GenerateConnectManifestRequest +from google.cloud.gkehub_v1beta1.types.membership import GenerateConnectManifestResponse +from google.cloud.gkehub_v1beta1.types.membership import GenerateExclusivityManifestRequest +from google.cloud.gkehub_v1beta1.types.membership import GenerateExclusivityManifestResponse +from google.cloud.gkehub_v1beta1.types.membership import GetMembershipRequest +from google.cloud.gkehub_v1beta1.types.membership import GkeCluster +from google.cloud.gkehub_v1beta1.types.membership import KubernetesMetadata +from google.cloud.gkehub_v1beta1.types.membership import KubernetesResource +from google.cloud.gkehub_v1beta1.types.membership import ListMembershipsRequest +from google.cloud.gkehub_v1beta1.types.membership import ListMembershipsResponse +from google.cloud.gkehub_v1beta1.types.membership import Membership +from google.cloud.gkehub_v1beta1.types.membership import MembershipEndpoint +from google.cloud.gkehub_v1beta1.types.membership import MembershipState +from google.cloud.gkehub_v1beta1.types.membership import MonitoringConfig +from google.cloud.gkehub_v1beta1.types.membership import MultiCloudCluster +from google.cloud.gkehub_v1beta1.types.membership import OnPremCluster +from google.cloud.gkehub_v1beta1.types.membership import OperationMetadata +from google.cloud.gkehub_v1beta1.types.membership import ResourceManifest +from google.cloud.gkehub_v1beta1.types.membership import ResourceOptions +from google.cloud.gkehub_v1beta1.types.membership import TypeMeta +from google.cloud.gkehub_v1beta1.types.membership import UpdateMembershipRequest +from google.cloud.gkehub_v1beta1.types.membership import ValidateExclusivityRequest +from google.cloud.gkehub_v1beta1.types.membership import ValidateExclusivityResponse + +__all__ = ('GkeHubMembershipServiceClient', + 'GkeHubMembershipServiceAsyncClient', + 'ApplianceCluster', + 'Authority', + 'ConnectAgent', + 'ConnectAgentResource', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'EdgeCluster', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'GenerateExclusivityManifestRequest', + 'GenerateExclusivityManifestResponse', + 'GetMembershipRequest', + 'GkeCluster', + 'KubernetesMetadata', + 'KubernetesResource', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'Membership', + 'MembershipEndpoint', + 'MembershipState', + 'MonitoringConfig', + 'MultiCloudCluster', + 'OnPremCluster', + 'OperationMetadata', + 'ResourceManifest', + 'ResourceOptions', + 'TypeMeta', + 'UpdateMembershipRequest', + 'ValidateExclusivityRequest', + 'ValidateExclusivityResponse', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub/gapic_version.py b/owl-bot-staging/v1beta1/google/cloud/gkehub/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/google/cloud/gkehub/py.typed b/owl-bot-staging/v1beta1/google/cloud/gkehub/py.typed new file mode 100644 index 0000000..7a6a6d0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-hub package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/__init__.py new file mode 100644 index 0000000..2e4f5ad --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.gke_hub_membership_service import GkeHubMembershipServiceClient +from .services.gke_hub_membership_service import GkeHubMembershipServiceAsyncClient + +from .types.membership import ApplianceCluster +from .types.membership import Authority +from .types.membership import ConnectAgent +from .types.membership import ConnectAgentResource +from .types.membership import CreateMembershipRequest +from .types.membership import DeleteMembershipRequest +from .types.membership import EdgeCluster +from .types.membership import GenerateConnectManifestRequest +from .types.membership import GenerateConnectManifestResponse +from .types.membership import GenerateExclusivityManifestRequest +from .types.membership import GenerateExclusivityManifestResponse +from .types.membership import GetMembershipRequest +from .types.membership import GkeCluster +from .types.membership import KubernetesMetadata +from .types.membership import KubernetesResource +from .types.membership import ListMembershipsRequest +from .types.membership import ListMembershipsResponse +from .types.membership import Membership +from .types.membership import MembershipEndpoint +from .types.membership import MembershipState +from .types.membership import MonitoringConfig +from .types.membership import MultiCloudCluster +from .types.membership import OnPremCluster +from .types.membership import OperationMetadata +from .types.membership import ResourceManifest +from .types.membership import ResourceOptions +from .types.membership import TypeMeta +from .types.membership import UpdateMembershipRequest +from .types.membership import ValidateExclusivityRequest +from .types.membership import ValidateExclusivityResponse + +__all__ = ( + 'GkeHubMembershipServiceAsyncClient', +'ApplianceCluster', +'Authority', +'ConnectAgent', +'ConnectAgentResource', +'CreateMembershipRequest', +'DeleteMembershipRequest', +'EdgeCluster', +'GenerateConnectManifestRequest', +'GenerateConnectManifestResponse', +'GenerateExclusivityManifestRequest', +'GenerateExclusivityManifestResponse', +'GetMembershipRequest', +'GkeCluster', +'GkeHubMembershipServiceClient', +'KubernetesMetadata', +'KubernetesResource', +'ListMembershipsRequest', +'ListMembershipsResponse', +'Membership', +'MembershipEndpoint', +'MembershipState', +'MonitoringConfig', +'MultiCloudCluster', +'OnPremCluster', +'OperationMetadata', +'ResourceManifest', +'ResourceOptions', +'TypeMeta', +'UpdateMembershipRequest', +'ValidateExclusivityRequest', +'ValidateExclusivityResponse', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_metadata.json new file mode 100644 index 0000000..5cfc89c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_metadata.json @@ -0,0 +1,148 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gkehub_v1beta1", + "protoPackage": "google.cloud.gkehub.v1beta1", + "schema": "1.0", + "services": { + "GkeHubMembershipService": { + "clients": { + "grpc": { + "libraryClient": "GkeHubMembershipServiceClient", + "rpcs": { + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GenerateExclusivityManifest": { + "methods": [ + "generate_exclusivity_manifest" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "ValidateExclusivity": { + "methods": [ + "validate_exclusivity" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GkeHubMembershipServiceAsyncClient", + "rpcs": { + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GenerateExclusivityManifest": { + "methods": [ + "generate_exclusivity_manifest" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "ValidateExclusivity": { + "methods": [ + "validate_exclusivity" + ] + } + } + }, + "rest": { + "libraryClient": "GkeHubMembershipServiceClient", + "rpcs": { + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "GenerateConnectManifest": { + "methods": [ + "generate_connect_manifest" + ] + }, + "GenerateExclusivityManifest": { + "methods": [ + "generate_exclusivity_manifest" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "UpdateMembership": { + "methods": [ + "update_membership" + ] + }, + "ValidateExclusivity": { + "methods": [ + "validate_exclusivity" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_version.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_version.py new file mode 100644 index 0000000..360a0d1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/google/cloud/gkehub_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/py.typed new file mode 100644 index 0000000..7a6a6d0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gke-hub package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/__init__.py new file mode 100644 index 0000000..89a37dc --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/__init__.py new file mode 100644 index 0000000..8921a31 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GkeHubMembershipServiceClient +from .async_client import GkeHubMembershipServiceAsyncClient + +__all__ = ( + 'GkeHubMembershipServiceClient', + 'GkeHubMembershipServiceAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/async_client.py new file mode 100644 index 0000000..4f65342 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/async_client.py @@ -0,0 +1,1720 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.gkehub_v1beta1 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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import pagers +from google.cloud.gkehub_v1beta1.types import membership +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 google.rpc import status_pb2 # type: ignore +from .transports.base import GkeHubMembershipServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GkeHubMembershipServiceGrpcAsyncIOTransport +from .client import GkeHubMembershipServiceClient + + +class GkeHubMembershipServiceAsyncClient: + """The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + """ + + _client: GkeHubMembershipServiceClient + + DEFAULT_ENDPOINT = GkeHubMembershipServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GkeHubMembershipServiceClient.DEFAULT_MTLS_ENDPOINT + + membership_path = staticmethod(GkeHubMembershipServiceClient.membership_path) + parse_membership_path = staticmethod(GkeHubMembershipServiceClient.parse_membership_path) + common_billing_account_path = staticmethod(GkeHubMembershipServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GkeHubMembershipServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GkeHubMembershipServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(GkeHubMembershipServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(GkeHubMembershipServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(GkeHubMembershipServiceClient.parse_common_organization_path) + common_project_path = staticmethod(GkeHubMembershipServiceClient.common_project_path) + parse_common_project_path = staticmethod(GkeHubMembershipServiceClient.parse_common_project_path) + common_location_path = staticmethod(GkeHubMembershipServiceClient.common_location_path) + parse_common_location_path = staticmethod(GkeHubMembershipServiceClient.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: + GkeHubMembershipServiceAsyncClient: The constructed client. + """ + return GkeHubMembershipServiceClient.from_service_account_info.__func__(GkeHubMembershipServiceAsyncClient, 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: + GkeHubMembershipServiceAsyncClient: The constructed client. + """ + return GkeHubMembershipServiceClient.from_service_account_file.__func__(GkeHubMembershipServiceAsyncClient, 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 GkeHubMembershipServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GkeHubMembershipServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GkeHubMembershipServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(GkeHubMembershipServiceClient).get_transport_class, type(GkeHubMembershipServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, GkeHubMembershipServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gke hub membership service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.GkeHubMembershipServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = GkeHubMembershipServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_memberships(self, + request: Optional[Union[membership.ListMembershipsRequest, 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.ListMembershipsAsyncPager: + r"""Lists Memberships in a given project and location. + + .. 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 gkehub_v1beta1 + + async def sample_list_memberships(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.ListMembershipsRequest, dict]]): + The request object. Request message for + ``GkeHubMembershipService.ListMemberships`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` + list memberships in all the regions. + + 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.gkehub_v1beta1.services.gke_hub_membership_service.pagers.ListMembershipsAsyncPager: + Response message for the + GkeHubMembershipService.ListMemberships method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.ListMembershipsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_memberships, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembershipsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership(self, + request: Optional[Union[membership.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Gets the details of a Membership. + + .. 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 gkehub_v1beta1 + + async def sample_get_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.GetMembershipRequest, dict]]): + The request object. Request message for + ``GkeHubMembershipService.GetMembership`` method. + name (:class:`str`): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.gkehub_v1beta1.types.Membership: + Membership contains information about + a member cluster. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.GetMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_membership(self, + request: Optional[Union[membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[membership.Membership] = None, + membership_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 Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + .. 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 gkehub_v1beta1 + + async def sample_create_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.CreateMembershipRequest, dict]]): + The request object. Request message for the + ``GkeHubMembershipService.CreateMembership`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Memberships will 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. + resource (:class:`google.cloud.gkehub_v1beta1.types.Membership`): + Required. The membership to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_id (:class:`str`): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``membership_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1beta1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, membership_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.CreateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if membership_id is not None: + request.membership_id = membership_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + membership.Membership, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_membership(self, + request: Optional[Union[membership.DeleteMembershipRequest, 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"""Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + .. 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 gkehub_v1beta1 + + async def sample_delete_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.DeleteMembershipRequest, dict]]): + The request object. Request message for + ``GkeHubMembershipService.DeleteMembership`` method. + name (:class:`str`): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.DeleteMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_membership(self, + request: Optional[Union[membership.UpdateMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[membership.Membership] = 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 an existing Membership. + + .. 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 gkehub_v1beta1 + + async def sample_update_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.UpdateMembershipRequest, dict]]): + The request object. Request message for + ``GkeHubMembershipService.UpdateMembership`` method. + name (:class:`str`): + Required. The membership resource name in the format: + ``projects/[project_id]/locations/global/memberships/[membership_id]`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.gkehub_v1beta1.types.Membership`): + Required. Only fields specified in update_mask are + updated. If you specify a field in the update_mask but + don't specify its value here that field will be deleted. + If you are updating a map field, set the value of a key + to null or empty string to delete the key from the map. + It's not possible to update a key's value to the empty + string. If you specify the update_mask to be a special + path "*", fully replaces all user-modifiable fields to + match ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask of fields to update. + At least one field path must be + specified in this mask. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1beta1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = membership.UpdateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_membership, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + membership.Membership, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_connect_manifest(self, + request: Optional[Union[membership.GenerateConnectManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateConnectManifestResponse: + r"""Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + .. 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 gkehub_v1beta1 + + async def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.GenerateConnectManifestRequest, dict]]): + The request object. Request message for + ``GkeHubMembershipService.GenerateConnectManifest`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + # Create or coerce a protobuf request object. + request = membership.GenerateConnectManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_connect_manifest, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def validate_exclusivity(self, + request: Optional[Union[membership.ValidateExclusivityRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.ValidateExclusivityResponse: + r"""ValidateExclusivity validates the state of + exclusivity in the cluster. The validation does not + depend on an existing Hub membership resource. + + .. 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 gkehub_v1beta1 + + async def sample_validate_exclusivity(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ValidateExclusivityRequest( + parent="parent_value", + intended_membership="intended_membership_value", + ) + + # Make the request + response = await client.validate_exclusivity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.ValidateExclusivityRequest, dict]]): + The request object. The request to validate the existing + state of the membership CR in the + cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.ValidateExclusivityResponse: + The response of exclusivity artifacts + validation result status. + + """ + # Create or coerce a protobuf request object. + request = membership.ValidateExclusivityRequest(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.validate_exclusivity, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_exclusivity_manifest(self, + request: Optional[Union[membership.GenerateExclusivityManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateExclusivityManifestResponse: + r"""GenerateExclusivityManifest generates the manifests + to update the exclusivity artifacts in the cluster if + needed. + + Exclusivity artifacts include the Membership custom + resource definition (CRD) and the singleton Membership + custom resource (CR). Combined with ValidateExclusivity, + exclusivity artifacts guarantee that a Kubernetes + cluster is only registered to a single GKE Hub. + + The Membership CRD is versioned, and may require + conversion when the GKE Hub API server begins serving a + newer version of the CRD and corresponding CR. The + response will be the converted CRD and CR if there are + any differences between the versions. + + .. 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 gkehub_v1beta1 + + async def sample_generate_exclusivity_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateExclusivityManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_exclusivity_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestRequest, dict]]): + The request object. The request to generate the manifests + for exclusivity artifacts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestResponse: + The response of the exclusivity + artifacts manifests for the client to + apply. + + """ + # Create or coerce a protobuf request object. + request = membership.GenerateExclusivityManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_exclusivity_manifest, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: 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._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + 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.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._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: 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._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: 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._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location 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 = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_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._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "GkeHubMembershipServiceAsyncClient": + 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__ = ( + "GkeHubMembershipServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py new file mode 100644 index 0000000..f395ce0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/client.py @@ -0,0 +1,1922 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.gkehub_v1beta1 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import pagers +from google.cloud.gkehub_v1beta1.types import membership +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 google.rpc import status_pb2 # type: ignore +from .transports.base import GkeHubMembershipServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GkeHubMembershipServiceGrpcTransport +from .transports.grpc_asyncio import GkeHubMembershipServiceGrpcAsyncIOTransport +from .transports.rest import GkeHubMembershipServiceRestTransport + + +class GkeHubMembershipServiceClientMeta(type): + """Metaclass for the GkeHubMembershipService 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[GkeHubMembershipServiceTransport]] + _transport_registry["grpc"] = GkeHubMembershipServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GkeHubMembershipServiceGrpcAsyncIOTransport + _transport_registry["rest"] = GkeHubMembershipServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[GkeHubMembershipServiceTransport]: + """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 GkeHubMembershipServiceClient(metaclass=GkeHubMembershipServiceClientMeta): + """The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gkehub.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GkeHubMembershipServiceClient: 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: + GkeHubMembershipServiceClient: 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) -> GkeHubMembershipServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GkeHubMembershipServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def membership_path(project: str,location: str,membership: str,) -> str: + """Returns a fully-qualified membership string.""" + return "projects/{project}/locations/{location}/memberships/{membership}".format(project=project, location=location, membership=membership, ) + + @staticmethod + def parse_membership_path(path: str) -> Dict[str,str]: + """Parses a membership path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/memberships/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment 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. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, GkeHubMembershipServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gke hub membership service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, GkeHubMembershipServiceTransport]): The + transport to use. 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. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, GkeHubMembershipServiceTransport): + # transport is a GkeHubMembershipServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_memberships(self, + request: Optional[Union[membership.ListMembershipsRequest, 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.ListMembershipsPager: + r"""Lists Memberships in a given project and location. + + .. 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 gkehub_v1beta1 + + def sample_list_memberships(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.ListMembershipsRequest, dict]): + The request object. Request message for + ``GkeHubMembershipService.ListMemberships`` method. + parent (str): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` + list memberships in all the regions. + + 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.gkehub_v1beta1.services.gke_hub_membership_service.pagers.ListMembershipsPager: + Response message for the + GkeHubMembershipService.ListMemberships method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.ListMembershipsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.ListMembershipsRequest): + request = membership.ListMembershipsRequest(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_memberships] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembershipsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership(self, + request: Optional[Union[membership.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Gets the details of a Membership. + + .. 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 gkehub_v1beta1 + + def sample_get_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.GetMembershipRequest, dict]): + The request object. Request message for + ``GkeHubMembershipService.GetMembership`` method. + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.gkehub_v1beta1.types.Membership: + Membership contains information about + a member cluster. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.GetMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.GetMembershipRequest): + request = membership.GetMembershipRequest(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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_membership(self, + request: Optional[Union[membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + resource: Optional[membership.Membership] = None, + membership_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 Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + .. 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 gkehub_v1beta1 + + def sample_create_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.CreateMembershipRequest, dict]): + The request object. Request message for the + ``GkeHubMembershipService.CreateMembership`` method. + parent (str): + Required. The parent (project and location) where the + Memberships will 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. + resource (google.cloud.gkehub_v1beta1.types.Membership): + Required. The membership to create. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_id (str): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``membership_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.gkehub_v1beta1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, membership_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.CreateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.CreateMembershipRequest): + request = membership.CreateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if resource is not None: + request.resource = resource + if membership_id is not None: + request.membership_id = membership_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + membership.Membership, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_membership(self, + request: Optional[Union[membership.DeleteMembershipRequest, 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"""Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + .. 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 gkehub_v1beta1 + + def sample_delete_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.DeleteMembershipRequest, dict]): + The request object. Request message for + ``GkeHubMembershipService.DeleteMembership`` method. + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.DeleteMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.DeleteMembershipRequest): + request = membership.DeleteMembershipRequest(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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_membership(self, + request: Optional[Union[membership.UpdateMembershipRequest, dict]] = None, + *, + name: Optional[str] = None, + resource: Optional[membership.Membership] = 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 an existing Membership. + + .. 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 gkehub_v1beta1 + + def sample_update_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.UpdateMembershipRequest, dict]): + The request object. Request message for + ``GkeHubMembershipService.UpdateMembership`` method. + name (str): + Required. The membership resource name in the format: + ``projects/[project_id]/locations/global/memberships/[membership_id]`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.gkehub_v1beta1.types.Membership): + Required. Only fields specified in update_mask are + updated. If you specify a field in the update_mask but + don't specify its value here that field will be deleted. + If you are updating a map field, set the value of a key + to null or empty string to delete the key from the map. + It's not possible to update a key's value to the empty + string. If you specify the update_mask to be a special + path "*", fully replaces all user-modifiable fields to + match ``resource``. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. + At least one field path must be + specified in this mask. + + 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.gkehub_v1beta1.types.Membership` + Membership contains information about a member cluster. + + """ + # 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, resource, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a membership.UpdateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.UpdateMembershipRequest): + request = membership.UpdateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if resource is not None: + request.resource = resource + 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_membership] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + membership.Membership, + metadata_type=membership.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_connect_manifest(self, + request: Optional[Union[membership.GenerateConnectManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateConnectManifestResponse: + r"""Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + .. 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 gkehub_v1beta1 + + def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.GenerateConnectManifestRequest, dict]): + The request object. Request message for + ``GkeHubMembershipService.GenerateConnectManifest`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a membership.GenerateConnectManifestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.GenerateConnectManifestRequest): + request = membership.GenerateConnectManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_connect_manifest] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def validate_exclusivity(self, + request: Optional[Union[membership.ValidateExclusivityRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.ValidateExclusivityResponse: + r"""ValidateExclusivity validates the state of + exclusivity in the cluster. The validation does not + depend on an existing Hub membership resource. + + .. 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 gkehub_v1beta1 + + def sample_validate_exclusivity(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ValidateExclusivityRequest( + parent="parent_value", + intended_membership="intended_membership_value", + ) + + # Make the request + response = client.validate_exclusivity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.ValidateExclusivityRequest, dict]): + The request object. The request to validate the existing + state of the membership CR in the + cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.ValidateExclusivityResponse: + The response of exclusivity artifacts + validation result status. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a membership.ValidateExclusivityRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.ValidateExclusivityRequest): + request = membership.ValidateExclusivityRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_exclusivity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_exclusivity_manifest(self, + request: Optional[Union[membership.GenerateExclusivityManifestRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.GenerateExclusivityManifestResponse: + r"""GenerateExclusivityManifest generates the manifests + to update the exclusivity artifacts in the cluster if + needed. + + Exclusivity artifacts include the Membership custom + resource definition (CRD) and the singleton Membership + custom resource (CR). Combined with ValidateExclusivity, + exclusivity artifacts guarantee that a Kubernetes + cluster is only registered to a single GKE Hub. + + The Membership CRD is versioned, and may require + conversion when the GKE Hub API server begins serving a + newer version of the CRD and corresponding CR. The + response will be the converted CRD and CR if there are + any differences between the versions. + + .. 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 gkehub_v1beta1 + + def sample_generate_exclusivity_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateExclusivityManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_exclusivity_manifest(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestRequest, dict]): + The request object. The request to generate the manifests + for exclusivity artifacts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestResponse: + The response of the exclusivity + artifacts manifests for the client to + apply. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a membership.GenerateExclusivityManifestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.GenerateExclusivityManifestRequest): + request = membership.GenerateExclusivityManifestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_exclusivity_manifest] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "GkeHubMembershipServiceClient": + 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),)), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # 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.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + 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),)), + ) + + # 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),)), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location 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 = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def 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),)), + ) + + # 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__ = ( + "GkeHubMembershipServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/pagers.py new file mode 100644 index 0000000..8838d63 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.gkehub_v1beta1.types import membership + + +class ListMembershipsPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1beta1.types.ListMembershipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1beta1.types.ListMembershipsResponse` + 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[..., membership.ListMembershipsResponse], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + 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.gkehub_v1beta1.types.ListMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1beta1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[membership.ListMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[membership.Membership]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMembershipsAsyncPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1beta1.types.ListMembershipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1beta1.types.ListMembershipsResponse` + 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[membership.ListMembershipsResponse]], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + 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.gkehub_v1beta1.types.ListMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1beta1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[membership.ListMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[membership.Membership]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + 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/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py new file mode 100644 index 0000000..d474aab --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GkeHubMembershipServiceTransport +from .grpc import GkeHubMembershipServiceGrpcTransport +from .grpc_asyncio import GkeHubMembershipServiceGrpcAsyncIOTransport +from .rest import GkeHubMembershipServiceRestTransport +from .rest import GkeHubMembershipServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GkeHubMembershipServiceTransport]] +_transport_registry['grpc'] = GkeHubMembershipServiceGrpcTransport +_transport_registry['grpc_asyncio'] = GkeHubMembershipServiceGrpcAsyncIOTransport +_transport_registry['rest'] = GkeHubMembershipServiceRestTransport + +__all__ = ( + 'GkeHubMembershipServiceTransport', + 'GkeHubMembershipServiceGrpcTransport', + 'GkeHubMembershipServiceGrpcAsyncIOTransport', + 'GkeHubMembershipServiceRestTransport', + 'GkeHubMembershipServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/base.py new file mode 100644 index 0000000..45c25f9 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/base.py @@ -0,0 +1,338 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_v1beta1 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.gkehub_v1beta1.types import membership +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 GkeHubMembershipServiceTransport(abc.ABC): + """Abstract transport class for GkeHubMembershipService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'gkehub.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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_memberships: gapic_v1.method.wrap_method( + self.list_memberships, + default_timeout=None, + client_info=client_info, + ), + self.get_membership: gapic_v1.method.wrap_method( + self.get_membership, + default_timeout=None, + client_info=client_info, + ), + self.create_membership: gapic_v1.method.wrap_method( + self.create_membership, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership: gapic_v1.method.wrap_method( + self.delete_membership, + default_timeout=None, + client_info=client_info, + ), + self.update_membership: gapic_v1.method.wrap_method( + self.update_membership, + default_timeout=None, + client_info=client_info, + ), + self.generate_connect_manifest: gapic_v1.method.wrap_method( + self.generate_connect_manifest, + default_timeout=None, + client_info=client_info, + ), + self.validate_exclusivity: gapic_v1.method.wrap_method( + self.validate_exclusivity, + default_timeout=None, + client_info=client_info, + ), + self.generate_exclusivity_manifest: gapic_v1.method.wrap_method( + self.generate_exclusivity_manifest, + 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_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + Union[ + membership.ListMembershipsResponse, + Awaitable[membership.ListMembershipsResponse] + ]]: + raise NotImplementedError() + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + Union[ + membership.Membership, + Awaitable[membership.Membership] + ]]: + raise NotImplementedError() + + @property + def create_membership(self) -> Callable[ + [membership.CreateMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_membership(self) -> Callable[ + [membership.UpdateMembershipRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_connect_manifest(self) -> Callable[ + [membership.GenerateConnectManifestRequest], + Union[ + membership.GenerateConnectManifestResponse, + Awaitable[membership.GenerateConnectManifestResponse] + ]]: + raise NotImplementedError() + + @property + def validate_exclusivity(self) -> Callable[ + [membership.ValidateExclusivityRequest], + Union[ + membership.ValidateExclusivityResponse, + Awaitable[membership.ValidateExclusivityResponse] + ]]: + raise NotImplementedError() + + @property + def generate_exclusivity_manifest(self) -> Callable[ + [membership.GenerateExclusivityManifestRequest], + Union[ + membership.GenerateExclusivityManifestResponse, + Awaitable[membership.GenerateExclusivityManifestResponse] + ]]: + 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 cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + 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 get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + 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__ = ( + 'GkeHubMembershipServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc.py new file mode 100644 index 0000000..1279968 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc.py @@ -0,0 +1,692 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.gkehub_v1beta1.types import membership +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 GkeHubMembershipServiceTransport, DEFAULT_CLIENT_INFO + + +class GkeHubMembershipServiceGrpcTransport(GkeHubMembershipServiceTransport): + """gRPC backend transport for GkeHubMembershipService. + + The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends 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 = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'gkehub.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_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + membership.ListMembershipsResponse]: + r"""Return a callable for the list memberships method over gRPC. + + Lists Memberships in a given project and location. + + Returns: + Callable[[~.ListMembershipsRequest], + ~.ListMembershipsResponse]: + 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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ListMemberships', + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + membership.Membership]: + r"""Return a callable for the get membership method over gRPC. + + Gets the details of a Membership. + + Returns: + Callable[[~.GetMembershipRequest], + ~.Membership]: + 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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GetMembership', + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def create_membership(self) -> Callable[ + [membership.CreateMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the create membership method over gRPC. + + Creates a new Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + Returns: + Callable[[~.CreateMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/CreateMembership', + request_serializer=membership.CreateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_membership'] + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete membership method over gRPC. + + Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + Returns: + Callable[[~.DeleteMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/DeleteMembership', + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_membership'] + + @property + def update_membership(self) -> Callable[ + [membership.UpdateMembershipRequest], + operations_pb2.Operation]: + r"""Return a callable for the update membership method over gRPC. + + Updates an existing Membership. + + Returns: + Callable[[~.UpdateMembershipRequest], + ~.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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/UpdateMembership', + request_serializer=membership.UpdateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_membership'] + + @property + def generate_connect_manifest(self) -> Callable[ + [membership.GenerateConnectManifestRequest], + membership.GenerateConnectManifestResponse]: + r"""Return a callable for the generate connect manifest method over gRPC. + + Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + Returns: + Callable[[~.GenerateConnectManifestRequest], + ~.GenerateConnectManifestResponse]: + 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_connect_manifest' not in self._stubs: + self._stubs['generate_connect_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateConnectManifest', + request_serializer=membership.GenerateConnectManifestRequest.serialize, + response_deserializer=membership.GenerateConnectManifestResponse.deserialize, + ) + return self._stubs['generate_connect_manifest'] + + @property + def validate_exclusivity(self) -> Callable[ + [membership.ValidateExclusivityRequest], + membership.ValidateExclusivityResponse]: + r"""Return a callable for the validate exclusivity method over gRPC. + + ValidateExclusivity validates the state of + exclusivity in the cluster. The validation does not + depend on an existing Hub membership resource. + + Returns: + Callable[[~.ValidateExclusivityRequest], + ~.ValidateExclusivityResponse]: + 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 'validate_exclusivity' not in self._stubs: + self._stubs['validate_exclusivity'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ValidateExclusivity', + request_serializer=membership.ValidateExclusivityRequest.serialize, + response_deserializer=membership.ValidateExclusivityResponse.deserialize, + ) + return self._stubs['validate_exclusivity'] + + @property + def generate_exclusivity_manifest(self) -> Callable[ + [membership.GenerateExclusivityManifestRequest], + membership.GenerateExclusivityManifestResponse]: + r"""Return a callable for the generate exclusivity manifest method over gRPC. + + GenerateExclusivityManifest generates the manifests + to update the exclusivity artifacts in the cluster if + needed. + + Exclusivity artifacts include the Membership custom + resource definition (CRD) and the singleton Membership + custom resource (CR). Combined with ValidateExclusivity, + exclusivity artifacts guarantee that a Kubernetes + cluster is only registered to a single GKE Hub. + + The Membership CRD is versioned, and may require + conversion when the GKE Hub API server begins serving a + newer version of the CRD and corresponding CR. The + response will be the converted CRD and CR if there are + any differences between the versions. + + Returns: + Callable[[~.GenerateExclusivityManifestRequest], + ~.GenerateExclusivityManifestResponse]: + 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_exclusivity_manifest' not in self._stubs: + self._stubs['generate_exclusivity_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateExclusivityManifest', + request_serializer=membership.GenerateExclusivityManifestRequest.serialize, + response_deserializer=membership.GenerateExclusivityManifestResponse.deserialize, + ) + return self._stubs['generate_exclusivity_manifest'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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 get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + 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 "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @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__ = ( + 'GkeHubMembershipServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..f598a56 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/grpc_asyncio.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 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.gkehub_v1beta1.types import membership +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 GkeHubMembershipServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import GkeHubMembershipServiceGrpcTransport + + +class GkeHubMembershipServiceGrpcAsyncIOTransport(GkeHubMembershipServiceTransport): + """gRPC AsyncIO backend transport for GkeHubMembershipService. + + The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends 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 = 'gkehub.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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + Awaitable[membership.ListMembershipsResponse]]: + r"""Return a callable for the list memberships method over gRPC. + + Lists Memberships in a given project and location. + + Returns: + Callable[[~.ListMembershipsRequest], + Awaitable[~.ListMembershipsResponse]]: + 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_memberships' not in self._stubs: + self._stubs['list_memberships'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ListMemberships', + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs['list_memberships'] + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + Awaitable[membership.Membership]]: + r"""Return a callable for the get membership method over gRPC. + + Gets the details of a Membership. + + Returns: + Callable[[~.GetMembershipRequest], + Awaitable[~.Membership]]: + 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_membership' not in self._stubs: + self._stubs['get_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GetMembership', + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs['get_membership'] + + @property + def create_membership(self) -> Callable[ + [membership.CreateMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create membership method over gRPC. + + Creates a new Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To register other clusters, follow the instructions at + https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster. + + Returns: + Callable[[~.CreateMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['create_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/CreateMembership', + request_serializer=membership.CreateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_membership'] + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete membership method over gRPC. + + Removes a Membership. + + **This is currently only supported for GKE clusters on Google + Cloud**. To unregister other clusters, follow the instructions + at + https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster. + + Returns: + Callable[[~.DeleteMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['delete_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/DeleteMembership', + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_membership'] + + @property + def update_membership(self) -> Callable[ + [membership.UpdateMembershipRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update membership method over gRPC. + + Updates an existing Membership. + + Returns: + Callable[[~.UpdateMembershipRequest], + 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_membership' not in self._stubs: + self._stubs['update_membership'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/UpdateMembership', + request_serializer=membership.UpdateMembershipRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_membership'] + + @property + def generate_connect_manifest(self) -> Callable[ + [membership.GenerateConnectManifestRequest], + Awaitable[membership.GenerateConnectManifestResponse]]: + r"""Return a callable for the generate connect manifest method over gRPC. + + Generates the manifest for deployment of the GKE connect agent. + + **This method is used internally by Google-provided libraries.** + Most clients should not need to call this method directly. + + Returns: + Callable[[~.GenerateConnectManifestRequest], + Awaitable[~.GenerateConnectManifestResponse]]: + 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_connect_manifest' not in self._stubs: + self._stubs['generate_connect_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateConnectManifest', + request_serializer=membership.GenerateConnectManifestRequest.serialize, + response_deserializer=membership.GenerateConnectManifestResponse.deserialize, + ) + return self._stubs['generate_connect_manifest'] + + @property + def validate_exclusivity(self) -> Callable[ + [membership.ValidateExclusivityRequest], + Awaitable[membership.ValidateExclusivityResponse]]: + r"""Return a callable for the validate exclusivity method over gRPC. + + ValidateExclusivity validates the state of + exclusivity in the cluster. The validation does not + depend on an existing Hub membership resource. + + Returns: + Callable[[~.ValidateExclusivityRequest], + Awaitable[~.ValidateExclusivityResponse]]: + 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 'validate_exclusivity' not in self._stubs: + self._stubs['validate_exclusivity'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ValidateExclusivity', + request_serializer=membership.ValidateExclusivityRequest.serialize, + response_deserializer=membership.ValidateExclusivityResponse.deserialize, + ) + return self._stubs['validate_exclusivity'] + + @property + def generate_exclusivity_manifest(self) -> Callable[ + [membership.GenerateExclusivityManifestRequest], + Awaitable[membership.GenerateExclusivityManifestResponse]]: + r"""Return a callable for the generate exclusivity manifest method over gRPC. + + GenerateExclusivityManifest generates the manifests + to update the exclusivity artifacts in the cluster if + needed. + + Exclusivity artifacts include the Membership custom + resource definition (CRD) and the singleton Membership + custom resource (CR). Combined with ValidateExclusivity, + exclusivity artifacts guarantee that a Kubernetes + cluster is only registered to a single GKE Hub. + + The Membership CRD is versioned, and may require + conversion when the GKE Hub API server begins serving a + newer version of the CRD and corresponding CR. The + response will be the converted CRD and CR if there are + any differences between the versions. + + Returns: + Callable[[~.GenerateExclusivityManifestRequest], + Awaitable[~.GenerateExclusivityManifestResponse]]: + 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_exclusivity_manifest' not in self._stubs: + self._stubs['generate_exclusivity_manifest'] = self.grpc_channel.unary_unary( + '/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateExclusivityManifest', + request_serializer=membership.GenerateExclusivityManifestRequest.serialize, + response_deserializer=membership.GenerateExclusivityManifestResponse.deserialize, + ) + return self._stubs['generate_exclusivity_manifest'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_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 "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @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 get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + 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 "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @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__ = ( + 'GkeHubMembershipServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py new file mode 100644 index 0000000..83a0d31 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/services/gke_hub_membership_service/transports/rest.py @@ -0,0 +1,1930 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.gkehub_v1beta1.types import membership +from google.longrunning import operations_pb2 # type: ignore + +from .base import GkeHubMembershipServiceTransport, 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 GkeHubMembershipServiceRestInterceptor: + """Interceptor for GkeHubMembershipService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the GkeHubMembershipServiceRestTransport. + + .. code-block:: python + class MyCustomGkeHubMembershipServiceInterceptor(GkeHubMembershipServiceRestInterceptor): + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_connect_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_connect_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_exclusivity_manifest(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_exclusivity_manifest(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_exclusivity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_exclusivity(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GkeHubMembershipServiceRestTransport(interceptor=MyCustomGkeHubMembershipServiceInterceptor()) + client = GkeHubMembershipServiceClient(transport=transport) + + + """ + def pre_create_membership(self, request: membership.CreateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_create_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_delete_membership(self, request: membership.DeleteMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_delete_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_generate_connect_manifest(self, request: membership.GenerateConnectManifestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.GenerateConnectManifestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_generate_connect_manifest(self, response: membership.GenerateConnectManifestResponse) -> membership.GenerateConnectManifestResponse: + """Post-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_generate_exclusivity_manifest(self, request: membership.GenerateExclusivityManifestRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.GenerateExclusivityManifestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_exclusivity_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_generate_exclusivity_manifest(self, response: membership.GenerateExclusivityManifestResponse) -> membership.GenerateExclusivityManifestResponse: + """Post-rpc interceptor for generate_exclusivity_manifest + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_get_membership(self, request: membership.GetMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_get_membership(self, response: membership.Membership) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_list_memberships(self, request: membership.ListMembershipsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_list_memberships(self, response: membership.ListMembershipsResponse) -> membership.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_update_membership(self, request: membership.UpdateMembershipRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.UpdateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_update_membership(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_validate_exclusivity(self, request: membership.ValidateExclusivityRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[membership.ValidateExclusivityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_exclusivity + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_validate_exclusivity(self, response: membership.ValidateExclusivityResponse) -> membership.ValidateExclusivityResponse: + """Post-rpc interceptor for validate_exclusivity + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHubMembershipService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> 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 GkeHubMembershipService 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 GkeHubMembershipService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GkeHubMembershipServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GkeHubMembershipServiceRestInterceptor + + +class GkeHubMembershipServiceRestTransport(GkeHubMembershipServiceTransport): + """REST backend transport for GkeHubMembershipService. + + The GKE Hub MembershipService handles the registration of many + Kubernetes clusters to Google Cloud, represented with the + [Membership][google.cloud.gkehub.v1beta1.Membership] resource. + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'gkehub.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[GkeHubMembershipServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GkeHubMembershipServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("CreateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "membershipId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.CreateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create membership method over HTTP. + + Args: + request (~.membership.CreateMembershipRequest): + The request object. Request message for the + ``GkeHubMembershipService.CreateMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/memberships', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_create_membership(request, metadata) + pb_request = membership.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _DeleteMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: membership.DeleteMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete membership method over HTTP. + + Args: + request (~.membership.DeleteMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.DeleteMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/memberships/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_membership(request, metadata) + pb_request = membership.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _GenerateConnectManifest(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GenerateConnectManifest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: membership.GenerateConnectManifestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.GenerateConnectManifestResponse: + r"""Call the generate connect manifest method over HTTP. + + Args: + request (~.membership.GenerateConnectManifestRequest): + The request object. Request message for + ``GkeHubMembershipService.GenerateConnectManifest`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest', + }, + ] + request, metadata = self._interceptor.pre_generate_connect_manifest(request, metadata) + pb_request = membership.GenerateConnectManifestRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.GenerateConnectManifestResponse() + pb_resp = membership.GenerateConnectManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_connect_manifest(resp) + return resp + + class _GenerateExclusivityManifest(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GenerateExclusivityManifest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: membership.GenerateExclusivityManifestRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.GenerateExclusivityManifestResponse: + r"""Call the generate exclusivity + manifest method over HTTP. + + Args: + request (~.membership.GenerateExclusivityManifestRequest): + The request object. The request to generate the manifests + for exclusivity artifacts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.GenerateExclusivityManifestResponse: + The response of the exclusivity + artifacts manifests for the client to + apply. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/memberships/*}:generateExclusivityManifest', + }, + ] + request, metadata = self._interceptor.pre_generate_exclusivity_manifest(request, metadata) + pb_request = membership.GenerateExclusivityManifestRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.GenerateExclusivityManifestResponse() + pb_resp = membership.GenerateExclusivityManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_exclusivity_manifest(resp) + return resp + + class _GetMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("GetMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: membership.GetMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.membership.GetMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.GetMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.Membership: + Membership contains information about + a member cluster. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/memberships/*}', + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = membership.GetMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _ListMemberships(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("ListMemberships") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, 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: membership.ListMembershipsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.membership.ListMembershipsRequest): + The request object. Request message for + ``GkeHubMembershipService.ListMemberships`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.ListMembershipsResponse: + Response message for the + ``GkeHubMembershipService.ListMemberships`` method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/memberships', + }, + ] + request, metadata = self._interceptor.pre_list_memberships(request, metadata) + pb_request = membership.ListMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.ListMembershipsResponse() + pb_resp = membership.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _UpdateMembership(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("UpdateMembership") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.UpdateMembershipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update membership method over HTTP. + + Args: + request (~.membership.UpdateMembershipRequest): + The request object. Request message for + ``GkeHubMembershipService.UpdateMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{name=projects/*/locations/*/memberships/*}', + 'body': 'resource', + }, + ] + request, metadata = self._interceptor.pre_update_membership(request, metadata) + pb_request = membership.UpdateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_membership(resp) + return resp + + class _ValidateExclusivity(GkeHubMembershipServiceRestStub): + def __hash__(self): + return hash("ValidateExclusivity") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "intendedMembership" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: membership.ValidateExclusivityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> membership.ValidateExclusivityResponse: + r"""Call the validate exclusivity method over HTTP. + + Args: + request (~.membership.ValidateExclusivityRequest): + The request object. The request to validate the existing + state of the membership CR in the + cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.membership.ValidateExclusivityResponse: + The response of exclusivity artifacts + validation result status. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/memberships:validateExclusivity', + }, + ] + request, metadata = self._interceptor.pre_validate_exclusivity(request, metadata) + pb_request = membership.ValidateExclusivityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.ValidateExclusivityResponse() + pb_resp = membership.ValidateExclusivityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_exclusivity(resp) + return resp + + @property + def create_membership(self) -> Callable[ + [membership.CreateMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership(self) -> Callable[ + [membership.DeleteMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_connect_manifest(self) -> Callable[ + [membership.GenerateConnectManifestRequest], + membership.GenerateConnectManifestResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateConnectManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_exclusivity_manifest(self) -> Callable[ + [membership.GenerateExclusivityManifestRequest], + membership.GenerateExclusivityManifestResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateExclusivityManifest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership(self) -> Callable[ + [membership.GetMembershipRequest], + membership.Membership]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships(self) -> Callable[ + [membership.ListMembershipsRequest], + membership.ListMembershipsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership(self) -> Callable[ + [membership.UpdateMembershipRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_exclusivity(self) -> Callable[ + [membership.ValidateExclusivityRequest], + membership.ValidateExclusivityResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateExclusivity(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(GkeHubMembershipServiceRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(GkeHubMembershipServiceRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(GkeHubMembershipServiceRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{resource=projects/*/locations/*/memberships/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(GkeHubMembershipServiceRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=projects/*/locations/*/memberships/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(GkeHubMembershipServiceRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=projects/*/locations/*/memberships/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(GkeHubMembershipServiceRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(GkeHubMembershipServiceRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(GkeHubMembershipServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(GkeHubMembershipServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'GkeHubMembershipServiceRestTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/__init__.py new file mode 100644 index 0000000..a01c22a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .membership import ( + ApplianceCluster, + Authority, + ConnectAgent, + ConnectAgentResource, + CreateMembershipRequest, + DeleteMembershipRequest, + EdgeCluster, + GenerateConnectManifestRequest, + GenerateConnectManifestResponse, + GenerateExclusivityManifestRequest, + GenerateExclusivityManifestResponse, + GetMembershipRequest, + GkeCluster, + KubernetesMetadata, + KubernetesResource, + ListMembershipsRequest, + ListMembershipsResponse, + Membership, + MembershipEndpoint, + MembershipState, + MonitoringConfig, + MultiCloudCluster, + OnPremCluster, + OperationMetadata, + ResourceManifest, + ResourceOptions, + TypeMeta, + UpdateMembershipRequest, + ValidateExclusivityRequest, + ValidateExclusivityResponse, +) + +__all__ = ( + 'ApplianceCluster', + 'Authority', + 'ConnectAgent', + 'ConnectAgentResource', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'EdgeCluster', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'GenerateExclusivityManifestRequest', + 'GenerateExclusivityManifestResponse', + 'GetMembershipRequest', + 'GkeCluster', + 'KubernetesMetadata', + 'KubernetesResource', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'Membership', + 'MembershipEndpoint', + 'MembershipState', + 'MonitoringConfig', + 'MultiCloudCluster', + 'OnPremCluster', + 'OperationMetadata', + 'ResourceManifest', + 'ResourceOptions', + 'TypeMeta', + 'UpdateMembershipRequest', + 'ValidateExclusivityRequest', + 'ValidateExclusivityResponse', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/membership.py b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/membership.py new file mode 100644 index 0000000..3a97273 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/gkehub_v1beta1/types/membership.py @@ -0,0 +1,1470 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.gkehub.v1beta1', + manifest={ + 'Membership', + 'MembershipEndpoint', + 'KubernetesResource', + 'ResourceOptions', + 'ResourceManifest', + 'GkeCluster', + 'OnPremCluster', + 'MultiCloudCluster', + 'EdgeCluster', + 'ApplianceCluster', + 'KubernetesMetadata', + 'Authority', + 'MonitoringConfig', + 'MembershipState', + 'ListMembershipsRequest', + 'ListMembershipsResponse', + 'GetMembershipRequest', + 'CreateMembershipRequest', + 'DeleteMembershipRequest', + 'UpdateMembershipRequest', + 'GenerateConnectManifestRequest', + 'GenerateConnectManifestResponse', + 'ConnectAgentResource', + 'TypeMeta', + 'ConnectAgent', + 'ValidateExclusivityRequest', + 'ValidateExclusivityResponse', + 'GenerateExclusivityManifestRequest', + 'GenerateExclusivityManifestResponse', + 'OperationMetadata', + }, +) + + +class Membership(proto.Message): + r"""Membership contains information about a member cluster. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The full, unique name of this Membership + resource in the format + ``projects/*/locations/*/memberships/{membership_id}``, set + during creation. + + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + labels (MutableMapping[str, str]): + Optional. GCP labels for this membership. + description (str): + Optional. Description of this membership, limited to 63 + characters. Must match the regex: + ``[a-zA-Z0-9][a-zA-Z0-9_\-\.\ ]*`` + endpoint (google.cloud.gkehub_v1beta1.types.MembershipEndpoint): + Optional. Endpoint information to reach this + member. + + This field is a member of `oneof`_ ``type``. + state (google.cloud.gkehub_v1beta1.types.MembershipState): + Output only. State of the Membership + resource. + authority (google.cloud.gkehub_v1beta1.types.Authority): + Optional. How to identify workloads from this + Membership. See the documentation on Workload + Identity for more details: + + https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was last + updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Membership was deleted. + external_id (str): + Optional. An externally-generated and managed ID for this + Membership. This ID may be modified after creation, but this + is not recommended. For GKE clusters, external_id is managed + by the Hub API and updates will be ignored. + + The ID must match the regex: + ``[a-zA-Z0-9][a-zA-Z0-9_\-\.]*`` + + If this Membership represents a Kubernetes cluster, this + value should be set to the UID of the ``kube-system`` + namespace object. + last_connection_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. For clusters using Connect, the + timestamp of the most recent connection + established with Google Cloud. This time is + updated every several minutes, not continuously. + For clusters that do not use GKE Connect, or + that have never connected successfully, this + field will be unset. + unique_id (str): + Output only. Google-generated UUID for this resource. This + is unique across all Membership resources. If a Membership + resource is deleted and another resource with the same name + is created, it gets a different unique_id. + infrastructure_type (google.cloud.gkehub_v1beta1.types.Membership.InfrastructureType): + Optional. The infrastructure type this + Membership is running on. + monitoring_config (google.cloud.gkehub_v1beta1.types.MonitoringConfig): + Optional. The monitoring config information + for this membership. + """ + class InfrastructureType(proto.Enum): + r"""Specifies the infrastructure type of a Membership. + Infrastructure type is used by Hub to control + infrastructure-specific behavior, including pricing. + + Each GKE distribution (on-GCP, on-Prem, on-X,...) will set this + field automatically, but Attached Clusters customers should + specify a type during registration. + + Values: + INFRASTRUCTURE_TYPE_UNSPECIFIED (0): + No type was specified. Some Hub functionality + may require a type be specified, and will not + support Memberships with this value. + ON_PREM (1): + Private infrastructure that is owned or + operated by customer. This includes GKE + distributions such as GKE-OnPrem and + GKE-OnBareMetal. + MULTI_CLOUD (2): + Public cloud infrastructure. + """ + INFRASTRUCTURE_TYPE_UNSPECIFIED = 0 + ON_PREM = 1 + MULTI_CLOUD = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + endpoint: 'MembershipEndpoint' = proto.Field( + proto.MESSAGE, + number=4, + oneof='type', + message='MembershipEndpoint', + ) + state: 'MembershipState' = proto.Field( + proto.MESSAGE, + number=5, + message='MembershipState', + ) + authority: 'Authority' = proto.Field( + proto.MESSAGE, + number=9, + message='Authority', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + external_id: str = proto.Field( + proto.STRING, + number=10, + ) + last_connection_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + unique_id: str = proto.Field( + proto.STRING, + number=12, + ) + infrastructure_type: InfrastructureType = proto.Field( + proto.ENUM, + number=13, + enum=InfrastructureType, + ) + monitoring_config: 'MonitoringConfig' = proto.Field( + proto.MESSAGE, + number=14, + message='MonitoringConfig', + ) + + +class MembershipEndpoint(proto.Message): + r"""MembershipEndpoint contains information needed to contact a + Kubernetes API, endpoint and any additional Kubernetes metadata. + + 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: + gke_cluster (google.cloud.gkehub_v1beta1.types.GkeCluster): + Optional. Specific information for a + GKE-on-GCP cluster. + + This field is a member of `oneof`_ ``type``. + on_prem_cluster (google.cloud.gkehub_v1beta1.types.OnPremCluster): + Optional. Specific information for a GKE + On-Prem cluster. An onprem user-cluster who has + no resourceLink is not allowed to use this + field, it should have a nil "type" instead. + + This field is a member of `oneof`_ ``type``. + multi_cloud_cluster (google.cloud.gkehub_v1beta1.types.MultiCloudCluster): + Optional. Specific information for a GKE + Multi-Cloud cluster. + + This field is a member of `oneof`_ ``type``. + edge_cluster (google.cloud.gkehub_v1beta1.types.EdgeCluster): + Optional. Specific information for a Google + Edge cluster. + + This field is a member of `oneof`_ ``type``. + appliance_cluster (google.cloud.gkehub_v1beta1.types.ApplianceCluster): + Optional. Specific information for a GDC Edge + Appliance cluster. + + This field is a member of `oneof`_ ``type``. + kubernetes_metadata (google.cloud.gkehub_v1beta1.types.KubernetesMetadata): + Output only. Useful Kubernetes-specific + metadata. + kubernetes_resource (google.cloud.gkehub_v1beta1.types.KubernetesResource): + Optional. The in-cluster Kubernetes Resources that should be + applied for a correctly registered cluster, in the steady + state. These resources: + + - Ensure that the cluster is exclusively registered to one + and only one Hub Membership. + - Propagate Workload Pool Information available in the + Membership Authority field. + - Ensure proper initial configuration of default Hub + Features. + """ + + gke_cluster: 'GkeCluster' = proto.Field( + proto.MESSAGE, + number=4, + oneof='type', + message='GkeCluster', + ) + on_prem_cluster: 'OnPremCluster' = proto.Field( + proto.MESSAGE, + number=7, + oneof='type', + message='OnPremCluster', + ) + multi_cloud_cluster: 'MultiCloudCluster' = proto.Field( + proto.MESSAGE, + number=8, + oneof='type', + message='MultiCloudCluster', + ) + edge_cluster: 'EdgeCluster' = proto.Field( + proto.MESSAGE, + number=9, + oneof='type', + message='EdgeCluster', + ) + appliance_cluster: 'ApplianceCluster' = proto.Field( + proto.MESSAGE, + number=10, + oneof='type', + message='ApplianceCluster', + ) + kubernetes_metadata: 'KubernetesMetadata' = proto.Field( + proto.MESSAGE, + number=5, + message='KubernetesMetadata', + ) + kubernetes_resource: 'KubernetesResource' = proto.Field( + proto.MESSAGE, + number=6, + message='KubernetesResource', + ) + + +class KubernetesResource(proto.Message): + r"""KubernetesResource contains the YAML manifests and + configuration for Membership Kubernetes resources in the + cluster. After CreateMembership or UpdateMembership, these + resources should be re-applied in the cluster. + + Attributes: + membership_cr_manifest (str): + Input only. The YAML representation of the + Membership CR. This field is ignored for GKE + clusters where Hub can read the CR directly. + + Callers should provide the CR that is currently + present in the cluster during CreateMembership + or UpdateMembership, or leave this field empty + if none exists. The CR manifest is used to + validate the cluster has not been registered + with another Membership. + membership_resources (MutableSequence[google.cloud.gkehub_v1beta1.types.ResourceManifest]): + Output only. Additional Kubernetes resources + that need to be applied to the cluster after + Membership creation, and after every update. + + This field is only populated in the Membership + returned from a successful long-running + operation from CreateMembership or + UpdateMembership. It is not populated during + normal GetMembership or ListMemberships + requests. To get the resource manifest after the + initial registration, the caller should make a + UpdateMembership call with an empty field mask. + connect_resources (MutableSequence[google.cloud.gkehub_v1beta1.types.ResourceManifest]): + Output only. The Kubernetes resources for + installing the GKE Connect agent + This field is only populated in the Membership + returned from a successful long-running + operation from CreateMembership or + UpdateMembership. It is not populated during + normal GetMembership or ListMemberships + requests. To get the resource manifest after the + initial registration, the caller should make a + UpdateMembership call with an empty field mask. + resource_options (google.cloud.gkehub_v1beta1.types.ResourceOptions): + Optional. Options for Kubernetes resource + generation. + """ + + membership_cr_manifest: str = proto.Field( + proto.STRING, + number=1, + ) + membership_resources: MutableSequence['ResourceManifest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ResourceManifest', + ) + connect_resources: MutableSequence['ResourceManifest'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ResourceManifest', + ) + resource_options: 'ResourceOptions' = proto.Field( + proto.MESSAGE, + number=4, + message='ResourceOptions', + ) + + +class ResourceOptions(proto.Message): + r"""ResourceOptions represent options for Kubernetes resource + generation. + + Attributes: + connect_version (str): + Optional. The Connect agent version to use for + connect_resources. Defaults to the latest GKE Connect + version. The version must be a currently supported version, + obsolete versions will be rejected. + v1beta1_crd (bool): + Optional. Use ``apiextensions/v1beta1`` instead of + ``apiextensions/v1`` for CustomResourceDefinition resources. + This option should be set for clusters with Kubernetes + apiserver versions <1.16. + k8s_version (str): + Optional. Major version of the Kubernetes cluster. This is + only used to determine which version to use for the + CustomResourceDefinition resources, + ``apiextensions/v1beta1`` or\ ``apiextensions/v1``. + """ + + connect_version: str = proto.Field( + proto.STRING, + number=1, + ) + v1beta1_crd: bool = proto.Field( + proto.BOOL, + number=2, + ) + k8s_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ResourceManifest(proto.Message): + r"""ResourceManifest represents a single Kubernetes resource to + be applied to the cluster. + + Attributes: + manifest (str): + YAML manifest of the resource. + cluster_scoped (bool): + Whether the resource provided in the manifest is + ``cluster_scoped``. If unset, the manifest is assumed to be + namespace scoped. + + This field is used for REST mapping when applying the + resource in a cluster. + """ + + manifest: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_scoped: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class GkeCluster(proto.Message): + r"""GkeCluster contains information specific to GKE clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the GCP resource for + the GKE cluster. For example: + //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster + + Zonal clusters are also supported. + cluster_missing (bool): + Output only. If cluster_missing is set then it denotes that + the GKE cluster no longer exists in the GKE Control Plane. + """ + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class OnPremCluster(proto.Message): + r"""OnPremCluster contains information specific to GKE On-Prem + clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the GCP resource for + the GKE On-Prem cluster. For example: + + //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/vmwareClusters/my-cluster + //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/bareMetalClusters/my-cluster + cluster_missing (bool): + Output only. If cluster_missing is set then it denotes that + API(gkeonprem.googleapis.com) resource for this GKE On-Prem + cluster no longer exists. + admin_cluster (bool): + Immutable. Whether the cluster is an admin + cluster. + cluster_type (google.cloud.gkehub_v1beta1.types.OnPremCluster.ClusterType): + Immutable. The on prem cluster's type. + """ + class ClusterType(proto.Enum): + r"""ClusterType describes on prem cluster's type. + + Values: + CLUSTERTYPE_UNSPECIFIED (0): + The ClusterType is not set. + BOOTSTRAP (1): + The ClusterType is bootstrap cluster. + HYBRID (2): + The ClusterType is baremetal hybrid cluster. + STANDALONE (3): + The ClusterType is baremetal standalone + cluster. + USER (4): + The ClusterType is user cluster. + """ + CLUSTERTYPE_UNSPECIFIED = 0 + BOOTSTRAP = 1 + HYBRID = 2 + STANDALONE = 3 + USER = 4 + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + admin_cluster: bool = proto.Field( + proto.BOOL, + number=3, + ) + cluster_type: ClusterType = proto.Field( + proto.ENUM, + number=4, + enum=ClusterType, + ) + + +class MultiCloudCluster(proto.Message): + r"""MultiCloudCluster contains information specific to GKE + Multi-Cloud clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the GCP resource for + the GKE Multi-Cloud cluster. For example: + + //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/awsClusters/my-cluster + //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/azureClusters/my-cluster + //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/attachedClusters/my-cluster + cluster_missing (bool): + Output only. If cluster_missing is set then it denotes that + API(gkemulticloud.googleapis.com) resource for this GKE + Multi-Cloud cluster no longer exists. + """ + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + cluster_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class EdgeCluster(proto.Message): + r"""EdgeCluster contains information specific to Google Edge + Clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the GCP resource for + the Edge Cluster. For example: + + //edgecontainer.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster + """ + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ApplianceCluster(proto.Message): + r"""ApplianceCluster contains information specific to GDC Edge + Appliance Clusters. + + Attributes: + resource_link (str): + Immutable. Self-link of the GCP resource for + the Appliance Cluster. For example: + + //transferappliance.googleapis.com/projects/my-project/locations/us-west1-a/appliances/my-appliance + """ + + resource_link: str = proto.Field( + proto.STRING, + number=1, + ) + + +class KubernetesMetadata(proto.Message): + r"""KubernetesMetadata provides informational metadata for + Memberships representing Kubernetes clusters. + + Attributes: + kubernetes_api_server_version (str): + Output only. Kubernetes API server version + string as reported by '/version'. + node_provider_id (str): + Output only. Node providerID as reported by the first node + in the list of nodes on the Kubernetes endpoint. On + Kubernetes platforms that support zero-node clusters (like + GKE-on-GCP), the node_count will be zero and the + node_provider_id will be empty. + node_count (int): + Output only. Node count as reported by + Kubernetes nodes resources. + vcpu_count (int): + Output only. vCPU count as reported by + Kubernetes nodes resources. + memory_mb (int): + Output only. The total memory capacity as + reported by the sum of all Kubernetes nodes + resources, defined in MB. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which these details were last + updated. This update_time is different from the + Membership-level update_time since EndpointDetails are + updated internally for API consumers. + """ + + kubernetes_api_server_version: str = proto.Field( + proto.STRING, + number=1, + ) + node_provider_id: str = proto.Field( + proto.STRING, + number=2, + ) + node_count: int = proto.Field( + proto.INT32, + number=3, + ) + vcpu_count: int = proto.Field( + proto.INT32, + number=4, + ) + memory_mb: int = proto.Field( + proto.INT32, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=100, + message=timestamp_pb2.Timestamp, + ) + + +class Authority(proto.Message): + r"""Authority encodes how Google will recognize identities from + this Membership. See the workload identity documentation for + more details: + + https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity + + Attributes: + issuer (str): + Optional. A JSON Web Token (JWT) issuer URI. ``issuer`` must + start with ``https://`` and be a valid URL with length <2000 + characters. + + If set, then Google will allow valid OIDC tokens from this + issuer to authenticate within the workload_identity_pool. + OIDC discovery will be performed on this URI to validate + tokens from the issuer. + + Clearing ``issuer`` disables Workload Identity. ``issuer`` + cannot be directly modified; it must be cleared (and + Workload Identity disabled) before using a new issuer (and + re-enabling Workload Identity). + workload_identity_pool (str): + Output only. The name of the workload identity pool in which + ``issuer`` will be recognized. + + There is a single Workload Identity Pool per Hub that is + shared between all Memberships that belong to that Hub. For + a Hub hosted in {PROJECT_ID}, the workload pool format is + ``{PROJECT_ID}.hub.id.goog``, although this is subject to + change in newer versions of this API. + identity_provider (str): + Output only. An identity provider that reflects the + ``issuer`` in the workload identity pool. + oidc_jwks (bytes): + Optional. OIDC verification keys for this Membership in JWKS + format (RFC 7517). + + When this field is set, OIDC discovery will NOT be performed + on ``issuer``, and instead OIDC tokens will be validated + using this field. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + workload_identity_pool: str = proto.Field( + proto.STRING, + number=2, + ) + identity_provider: str = proto.Field( + proto.STRING, + number=3, + ) + oidc_jwks: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + +class MonitoringConfig(proto.Message): + r"""This field informs Fleet-based applications/services/UIs with + the necessary information for where each underlying Cluster + reports its metrics. + + Attributes: + project_id (str): + Immutable. Project used to report Metrics + location (str): + Immutable. Location used to report Metrics + cluster (str): + Immutable. Cluster name used to report metrics. For Anthos + on VMWare/Baremetal, it would be in format + ``memberClusters/cluster_name``; And for Anthos on + MultiCloud, it would be in format + ``{azureClusters, awsClusters}/cluster_name``. + kubernetes_metrics_prefix (str): + Kubernetes system metrics, if available, are + written to this prefix. This defaults to + kubernetes.io for GKE, and kubernetes.io/anthos + for Anthos eventually. Noted: Anthos MultiCloud + will have kubernetes.io prefix today but will + migration to be under kubernetes.io/anthos + cluster_hash (str): + Immutable. Cluster hash, this is a unique + string generated by google code, which does not + contain any PII, which we can use to reference + the cluster. This is expected to be created by + the monitoring stack and persisted into the + Cluster object as well as to GKE-Hub. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + cluster: str = proto.Field( + proto.STRING, + number=3, + ) + kubernetes_metrics_prefix: str = proto.Field( + proto.STRING, + number=4, + ) + cluster_hash: str = proto.Field( + proto.STRING, + number=5, + ) + + +class MembershipState(proto.Message): + r"""State of the Membership resource. + + Attributes: + code (google.cloud.gkehub_v1beta1.types.MembershipState.Code): + Output only. The current state of the + Membership resource. + description (str): + This field is never set by the Hub Service. + update_time (google.protobuf.timestamp_pb2.Timestamp): + This field is never set by the Hub Service. + """ + class Code(proto.Enum): + r"""Code describes the state of a Membership resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The cluster is being registered. + READY (2): + The cluster is registered. + DELETING (3): + The cluster is being unregistered. + UPDATING (4): + The Membership is being updated. + SERVICE_UPDATING (5): + The Membership is being updated by the Hub + Service. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + SERVICE_UPDATING = 5 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ListMembershipsRequest(proto.Message): + r"""Request message for ``GkeHubMembershipService.ListMemberships`` + method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Memberships will be listed. Specified in the format + ``projects/*/locations/*``. ``projects/*/locations/-`` list + memberships in all the regions. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListMemberships`` which specifies the position in the list + from where to continue listing the resources. + filter (str): + Optional. Lists Memberships that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. + + Examples: + + - Name is ``bar`` in project ``foo-proj`` and location + ``global``: + + name = + "projects/foo-proj/locations/global/membership/bar" + + - Memberships that have a label called ``foo``: + + labels.foo:\* + + - Memberships that have a label called ``foo`` whose value + is ``bar``: + + labels.foo = bar + + - Memberships in the CREATING state: + + state = CREATING + order_by (str): + Optional. One or more fields to compare and + use to sort the output. 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 ListMembershipsResponse(proto.Message): + r"""Response message for the ``GkeHubMembershipService.ListMemberships`` + method. + + Attributes: + resources (MutableSequence[google.cloud.gkehub_v1beta1.types.Membership]): + The list of matching Memberships. + next_page_token (str): + A token to request the next page of resources from the + ``ListMemberships`` method. The value of an empty string + means that there are no more resources to return. + unreachable (MutableSequence[str]): + List of locations that could not be reached + while fetching this list. + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence['Membership'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Membership', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetMembershipRequest(proto.Message): + r"""Request message for ``GkeHubMembershipService.GetMembership`` + method. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMembershipRequest(proto.Message): + r"""Request message for the ``GkeHubMembershipService.CreateMembership`` + method. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Memberships will be created. Specified in the format + ``projects/*/locations/*``. + membership_id (str): + Required. Client chosen ID for the membership. + ``membership_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + resource (google.cloud.gkehub_v1beta1.types.Membership): + Required. The membership to create. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + membership_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource: 'Membership' = proto.Field( + proto.MESSAGE, + number=3, + message='Membership', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteMembershipRequest(proto.Message): + r"""Request message for ``GkeHubMembershipService.DeleteMembership`` + method. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any subresource + from this Membership will also be deleted. + Otherwise, the request will only work if the + Membership has no subresource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class UpdateMembershipRequest(proto.Message): + r"""Request message for ``GkeHubMembershipService.UpdateMembership`` + method. + + Attributes: + name (str): + Required. The membership resource name in the format: + ``projects/[project_id]/locations/global/memberships/[membership_id]`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update. At least + one field path must be specified in this mask. + resource (google.cloud.gkehub_v1beta1.types.Membership): + Required. Only fields specified in update_mask are updated. + If you specify a field in the update_mask but don't specify + its value here that field will be deleted. If you are + updating a map field, set the value of a key to null or + empty string to delete the key from the map. It's not + possible to update a key's value to the empty string. If you + specify the update_mask to be a special path "*", fully + replaces all user-modifiable fields to match ``resource``. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. The server will guarantee that for at + least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + resource: 'Membership' = proto.Field( + proto.MESSAGE, + number=3, + message='Membership', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GenerateConnectManifestRequest(proto.Message): + r"""Request message for + ``GkeHubMembershipService.GenerateConnectManifest`` method. + + Attributes: + name (str): + Required. The Membership resource name the Agent will + associate with, in the format + ``projects/*/locations/*/memberships/*``. + connect_agent (google.cloud.gkehub_v1beta1.types.ConnectAgent): + Optional. The connect agent to generate + manifest for. + version (str): + Optional. The Connect agent version to use. + Defaults to the most current version. + is_upgrade (bool): + Optional. If true, generate the resources for + upgrade only. Some resources generated only for + installation (e.g. secrets) will be excluded. + registry (str): + Optional. The registry to fetch the connect + agent image from. Defaults to gcr.io/gkeconnect. + image_pull_secret_content (bytes): + Optional. The image pull secret content for + the registry, if not public. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + connect_agent: 'ConnectAgent' = proto.Field( + proto.MESSAGE, + number=2, + message='ConnectAgent', + ) + version: str = proto.Field( + proto.STRING, + number=3, + ) + is_upgrade: bool = proto.Field( + proto.BOOL, + number=4, + ) + registry: str = proto.Field( + proto.STRING, + number=5, + ) + image_pull_secret_content: bytes = proto.Field( + proto.BYTES, + number=6, + ) + + +class GenerateConnectManifestResponse(proto.Message): + r"""GenerateConnectManifestResponse contains manifest information + for installing/upgrading a Connect agent. + + Attributes: + manifest (MutableSequence[google.cloud.gkehub_v1beta1.types.ConnectAgentResource]): + The ordered list of Kubernetes resources that + need to be applied to the cluster for GKE + Connect agent installation/upgrade. + """ + + manifest: MutableSequence['ConnectAgentResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConnectAgentResource', + ) + + +class ConnectAgentResource(proto.Message): + r"""ConnectAgentResource represents a Kubernetes resource + manifest for Connect Agent deployment. + + Attributes: + type_ (google.cloud.gkehub_v1beta1.types.TypeMeta): + Kubernetes type of the resource. + manifest (str): + YAML manifest of the resource. + """ + + type_: 'TypeMeta' = proto.Field( + proto.MESSAGE, + number=1, + message='TypeMeta', + ) + manifest: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TypeMeta(proto.Message): + r"""TypeMeta is the type information needed for content + unmarshalling of Kubernetes resources in the manifest. + + Attributes: + kind (str): + Kind of the resource (e.g. Deployment). + api_version (str): + APIVersion of the resource (e.g. v1). + """ + + kind: str = proto.Field( + proto.STRING, + number=1, + ) + api_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ConnectAgent(proto.Message): + r"""The information required from end users to use GKE Connect. + + Attributes: + name (str): + Do not set. + proxy (bytes): + Optional. URI of a proxy if connectivity from the agent to + gkeconnect.googleapis.com requires the use of a proxy. + Format must be in the form ``http(s)://{proxy_address}``, + depending on the HTTP/HTTPS protocol supported by the proxy. + This will direct the connect agent's outbound traffic + through a HTTP(S) proxy. + namespace (str): + Optional. Namespace for GKE Connect agent resources. + Defaults to ``gke-connect``. + + The Connect Agent is authorized automatically when run in + the default namespace. Otherwise, explicit authorization + must be granted with an additional IAM binding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + proxy: bytes = proto.Field( + proto.BYTES, + number=2, + ) + namespace: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ValidateExclusivityRequest(proto.Message): + r"""The request to validate the existing state of the membership + CR in the cluster. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Memberships will be created. Specified in the format + ``projects/*/locations/*``. + cr_manifest (str): + Optional. The YAML of the membership CR in + the cluster. Empty if the membership CR does not + exist. + intended_membership (str): + Required. The intended membership name under the ``parent``. + This method only does validation in anticipation of a + CreateMembership call with the same name. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cr_manifest: str = proto.Field( + proto.STRING, + number=2, + ) + intended_membership: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ValidateExclusivityResponse(proto.Message): + r"""The response of exclusivity artifacts validation result + status. + + Attributes: + status (google.rpc.status_pb2.Status): + The validation result. + + - ``OK`` means that exclusivity is validated, assuming the + manifest produced by GenerateExclusivityManifest is + successfully applied. + - ``ALREADY_EXISTS`` means that the Membership CRD is + already owned by another Hub. See ``status.message`` for + more information. + """ + + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + + +class GenerateExclusivityManifestRequest(proto.Message): + r"""The request to generate the manifests for exclusivity + artifacts. + + Attributes: + name (str): + Required. The Membership resource name in the format + ``projects/*/locations/*/memberships/*``. + crd_manifest (str): + Optional. The YAML manifest of the membership CRD retrieved + by ``kubectl get customresourcedefinitions membership``. + Leave empty if the resource does not exist. + cr_manifest (str): + Optional. The YAML manifest of the membership CR retrieved + by ``kubectl get memberships membership``. Leave empty if + the resource does not exist. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + crd_manifest: str = proto.Field( + proto.STRING, + number=2, + ) + cr_manifest: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateExclusivityManifestResponse(proto.Message): + r"""The response of the exclusivity artifacts manifests for the + client to apply. + + Attributes: + crd_manifest (str): + The YAML manifest of the membership CRD to + apply if a newer version of the CRD is + available. Empty if no update needs to be + applied. + cr_manifest (str): + The YAML manifest of the membership CR to + apply if a new version of the CR is available. + Empty if no update needs to be applied. + """ + + crd_manifest: str = proto.Field( + proto.STRING, + number=1, + ) + cr_manifest: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_detail (str): + Output only. Human-readable status of the + operation, if any. + cancel_requested (bool): + Output only. 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): + Output only. API version used to start the + operation. + """ + + 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 0000000..a51a317 --- /dev/null +++ b/owl-bot-staging/v1beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/gkehub_v1beta1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@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( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + '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, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py new file mode 100644 index 0000000..d0f7a78 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_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 gkehub_v1beta1 + + +async def sample_create_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py new file mode 100644 index 0000000..60545ab --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_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 gkehub_v1beta1 + + +def sample_create_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.CreateMembershipRequest( + parent="parent_value", + membership_id="membership_id_value", + ) + + # Make the request + operation = client.create_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py new file mode 100644 index 0000000..954d663 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_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 gkehub_v1beta1 + + +async def sample_delete_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py new file mode 100644 index 0000000..ec2d459 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_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 gkehub_v1beta1 + + +def sample_delete_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py new file mode 100644 index 0000000..5ab5106 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateConnectManifest +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_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 gkehub_v1beta1 + + +async def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py new file mode 100644 index 0000000..00cb0e7 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateConnectManifest +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_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 gkehub_v1beta1 + + +def sample_generate_connect_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateConnectManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_connect_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py new file mode 100644 index 0000000..549cf30 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateExclusivityManifest +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_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 gkehub_v1beta1 + + +async def sample_generate_exclusivity_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateExclusivityManifestRequest( + name="name_value", + ) + + # Make the request + response = await client.generate_exclusivity_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py new file mode 100644 index 0000000..e7acde7 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GenerateExclusivityManifest +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_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 gkehub_v1beta1 + + +def sample_generate_exclusivity_manifest(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GenerateExclusivityManifestRequest( + name="name_value", + ) + + # Make the request + response = client.generate_exclusivity_manifest(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py new file mode 100644 index 0000000..d4ad7e9 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_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 gkehub_v1beta1 + + +async def sample_get_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py new file mode 100644 index 0000000..21fa0de --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_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 gkehub_v1beta1 + + +def sample_get_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py new file mode 100644 index 0000000..1cc8f86 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_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 gkehub_v1beta1 + + +async def sample_list_memberships(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py new file mode 100644 index 0000000..b363482 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_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 gkehub_v1beta1 + + +def sample_list_memberships(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py new file mode 100644 index 0000000..855652a --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_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 gkehub_v1beta1 + + +async def sample_update_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py new file mode 100644 index 0000000..bae6cb1 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMembership +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_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 gkehub_v1beta1 + + +def sample_update_membership(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.UpdateMembershipRequest( + name="name_value", + ) + + # Make the request + operation = client.update_membership(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py new file mode 100644 index 0000000..bc0fc74 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ValidateExclusivity +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_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 gkehub_v1beta1 + + +async def sample_validate_exclusivity(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ValidateExclusivityRequest( + parent="parent_value", + intended_membership="intended_membership_value", + ) + + # Make the request + response = await client.validate_exclusivity(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py new file mode 100644 index 0000000..f216733 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ValidateExclusivity +# 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-gke-hub + + +# [START gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_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 gkehub_v1beta1 + + +def sample_validate_exclusivity(): + # Create a client + client = gkehub_v1beta1.GkeHubMembershipServiceClient() + + # Initialize request argument(s) + request = gkehub_v1beta1.ValidateExclusivityRequest( + parent="parent_value", + intended_membership="intended_membership_value", + ) + + # Make the request + response = client.validate_exclusivity(request=request) + + # Handle the response + print(response) + +# [END gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json b/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json new file mode 100644 index 0000000..5f7f541 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json @@ -0,0 +1,1311 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.gkehub.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-gke-hub", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.create_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.CreateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1beta1.types.Membership" + }, + { + "name": "membership_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_membership" + }, + "description": "Sample for CreateMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.create_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.CreateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1beta1.types.Membership" + }, + { + "name": "membership_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_membership" + }, + "description": "Sample for CreateMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_CreateMembership_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1beta1_generated_gke_hub_membership_service_create_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.DeleteMembershipRequest" + }, + { + "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_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.DeleteMembershipRequest" + }, + { + "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_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_DeleteMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_delete_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_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": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GenerateConnectManifest_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": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_connect_manifest_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.generate_exclusivity_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GenerateExclusivityManifest", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GenerateExclusivityManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestResponse", + "shortName": "generate_exclusivity_manifest" + }, + "description": "Sample for GenerateExclusivityManifest", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_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": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.generate_exclusivity_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GenerateExclusivityManifest", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GenerateExclusivityManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.GenerateExclusivityManifestResponse", + "shortName": "generate_exclusivity_manifest" + }, + "description": "Sample for GenerateExclusivityManifest", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GenerateExclusivityManifest_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": "gkehub_v1beta1_generated_gke_hub_membership_service_generate_exclusivity_manifest_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GetMembershipRequest" + }, + { + "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.gkehub_v1beta1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.GetMembershipRequest" + }, + { + "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.gkehub_v1beta1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_GetMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_get_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.ListMembershipsRequest" + }, + { + "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.gkehub_v1beta1.services.gke_hub_membership_service.pagers.ListMembershipsAsyncPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_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": "gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.ListMembershipsRequest" + }, + { + "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.gkehub_v1beta1.services.gke_hub_membership_service.pagers.ListMembershipsPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_ListMemberships_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": "gkehub_v1beta1_generated_gke_hub_membership_service_list_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.update_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.UpdateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.UpdateMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1beta1.types.Membership" + }, + { + "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_membership" + }, + "description": "Sample for UpdateMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.update_membership", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.UpdateMembership", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "UpdateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.UpdateMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1beta1.types.Membership" + }, + { + "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_membership" + }, + "description": "Sample for UpdateMembership", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_UpdateMembership_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": "gkehub_v1beta1_generated_gke_hub_membership_service_update_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient", + "shortName": "GkeHubMembershipServiceAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceAsyncClient.validate_exclusivity", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.ValidateExclusivity", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "ValidateExclusivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.ValidateExclusivityRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.ValidateExclusivityResponse", + "shortName": "validate_exclusivity" + }, + "description": "Sample for ValidateExclusivity", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_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": "gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient", + "shortName": "GkeHubMembershipServiceClient" + }, + "fullName": "google.cloud.gkehub_v1beta1.GkeHubMembershipServiceClient.validate_exclusivity", + "method": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService.ValidateExclusivity", + "service": { + "fullName": "google.cloud.gkehub.v1beta1.GkeHubMembershipService", + "shortName": "GkeHubMembershipService" + }, + "shortName": "ValidateExclusivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1beta1.types.ValidateExclusivityRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.gkehub_v1beta1.types.ValidateExclusivityResponse", + "shortName": "validate_exclusivity" + }, + "description": "Sample for ValidateExclusivity", + "file": "gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1beta1_generated_GkeHubMembershipService_ValidateExclusivity_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": "gkehub_v1beta1_generated_gke_hub_membership_service_validate_exclusivity_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta1/scripts/fixup_gkehub_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_gkehub_v1beta1_keywords.py new file mode 100644 index 0000000..737cb10 --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_gkehub_v1beta1_keywords.py @@ -0,0 +1,183 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 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 gkehubCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_membership': ('parent', 'membership_id', 'resource', 'request_id', ), + 'delete_membership': ('name', 'request_id', 'force', ), + 'generate_connect_manifest': ('name', 'connect_agent', 'version', 'is_upgrade', 'registry', 'image_pull_secret_content', ), + 'generate_exclusivity_manifest': ('name', 'crd_manifest', 'cr_manifest', ), + 'get_membership': ('name', ), + 'list_memberships': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_membership': ('name', 'update_mask', 'resource', 'request_id', ), + 'validate_exclusivity': ('parent', 'intended_membership', 'cr_manifest', ), + } + + 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=gkehubCallTransformer(), +): + """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 gkehub 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 0000000..05684c0 --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-gke-hub' + + +description = "Google Cloud Gke Hub API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/gkehub/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +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.0, <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.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=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/python-gke-hub" + +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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- 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/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- 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/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- 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/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- 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/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- 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/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/tests/unit/gapic/gkehub_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/__init__.py new file mode 100644 index 0000000..1b4db44 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 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/v1beta1/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py new file mode 100644 index 0000000..94be30a --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/gkehub_v1beta1/test_gke_hub_membership_service.py @@ -0,0 +1,6779 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 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.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import GkeHubMembershipServiceAsyncClient +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import GkeHubMembershipServiceClient +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import pagers +from google.cloud.gkehub_v1beta1.services.gke_hub_membership_service import transports +from google.cloud.gkehub_v1beta1.types import membership +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 +from google.rpc import status_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 + + +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 GkeHubMembershipServiceClient._get_default_mtls_endpoint(None) is None + assert GkeHubMembershipServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GkeHubMembershipServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GkeHubMembershipServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GkeHubMembershipServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GkeHubMembershipServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (GkeHubMembershipServiceClient, "grpc"), + (GkeHubMembershipServiceAsyncClient, "grpc_asyncio"), + (GkeHubMembershipServiceClient, "rest"), +]) +def test_gke_hub_membership_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 == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkehub.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.GkeHubMembershipServiceGrpcTransport, "grpc"), + (transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GkeHubMembershipServiceRestTransport, "rest"), +]) +def test_gke_hub_membership_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", [ + (GkeHubMembershipServiceClient, "grpc"), + (GkeHubMembershipServiceAsyncClient, "grpc_asyncio"), + (GkeHubMembershipServiceClient, "rest"), +]) +def test_gke_hub_membership_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 == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://gkehub.googleapis.com' + ) + + +def test_gke_hub_membership_service_client_get_transport_class(): + transport = GkeHubMembershipServiceClient.get_transport_class() + available_transports = [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceRestTransport, + ] + assert transport in available_transports + + transport = GkeHubMembershipServiceClient.get_transport_class("grpc") + assert transport == transports.GkeHubMembershipServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc"), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceRestTransport, "rest"), +]) +@mock.patch.object(GkeHubMembershipServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceClient)) +@mock.patch.object(GkeHubMembershipServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceAsyncClient)) +def test_gke_hub_membership_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(GkeHubMembershipServiceClient, '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(GkeHubMembershipServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc", "true"), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc", "false"), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceRestTransport, "rest", "true"), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(GkeHubMembershipServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceClient)) +@mock.patch.object(GkeHubMembershipServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_gke_hub_membership_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + GkeHubMembershipServiceClient, GkeHubMembershipServiceAsyncClient +]) +@mock.patch.object(GkeHubMembershipServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceClient)) +@mock.patch.object(GkeHubMembershipServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GkeHubMembershipServiceAsyncClient)) +def test_gke_hub_membership_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc"), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceRestTransport, "rest"), +]) +def test_gke_hub_membership_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc", grpc_helpers), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceRestTransport, "rest", None), +]) +def test_gke_hub_membership_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_gke_hub_membership_service_client_client_options_from_dict(): + with mock.patch('google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GkeHubMembershipServiceClient( + 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", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport, "grpc", grpc_helpers), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_gke_hub_membership_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "gkehub.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="gkehub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + membership.ListMembershipsRequest, + dict, +]) +def test_list_memberships(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_memberships_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 = GkeHubMembershipServiceClient( + 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_memberships), + '__call__') as call: + client.list_memberships() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + +@pytest.mark.asyncio +async def test_list_memberships_async(transport: str = 'grpc_asyncio', request_type=membership.ListMembershipsRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_memberships_async_from_dict(): + await test_list_memberships_async(request_type=dict) + + +def test_list_memberships_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = membership.ListMembershipsResponse() + client.list_memberships(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_memberships_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.ListMembershipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse()) + await client.list_memberships(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_memberships_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_memberships( + 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_memberships_flattened_error(): + client = GkeHubMembershipServiceClient( + 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_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_memberships_flattened_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ListMembershipsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_memberships( + 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_memberships_flattened_error_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_pager(transport_name: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_memberships(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) +def test_list_memberships_pages(transport_name: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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_memberships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + pages = list(client.list_memberships(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_memberships_async_pager(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_memberships(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, membership.Membership) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_memberships_async_pages(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + 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_memberships(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", [ + membership.GetMembershipRequest, + dict, +]) +def test_get_membership(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + infrastructure_type=membership.Membership.InfrastructureType.ON_PREM, + ) + response = client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + assert response.infrastructure_type == membership.Membership.InfrastructureType.ON_PREM + + +def test_get_membership_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 = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + client.get_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + +@pytest.mark.asyncio +async def test_get_membership_async(transport: str = 'grpc_asyncio', request_type=membership.GetMembershipRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + infrastructure_type=membership.Membership.InfrastructureType.ON_PREM, + )) + response = await client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + assert response.infrastructure_type == membership.Membership.InfrastructureType.ON_PREM + + +@pytest.mark.asyncio +async def test_get_membership_async_from_dict(): + await test_get_membership_async(request_type=dict) + + +def test_get_membership_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = membership.Membership() + client.get_membership(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_membership_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.GetMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + await client.get_membership(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_membership_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership( + 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_membership_flattened_error(): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_membership_flattened_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.Membership()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership( + 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_membership_flattened_error_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + membership.CreateMembershipRequest, + dict, +]) +def test_create_membership(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_membership_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 = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + client.create_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.CreateMembershipRequest() + +@pytest.mark.asyncio +async def test_create_membership_async(transport: str = 'grpc_asyncio', request_type=membership.CreateMembershipRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_membership_async_from_dict(): + await test_create_membership_async(request_type=dict) + + +def test_create_membership_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_membership(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_membership_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.CreateMembershipRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_membership(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_membership_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__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_membership( + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_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].resource + mock_val = membership.Membership(name='name_value') + assert arg == mock_val + arg = args[0].membership_id + mock_val = 'membership_id_value' + assert arg == mock_val + + +def test_create_membership_flattened_error(): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_id_value', + ) + +@pytest.mark.asyncio +async def test_create_membership_flattened_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), + '__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_membership( + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_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].resource + mock_val = membership.Membership(name='name_value') + assert arg == mock_val + arg = args[0].membership_id + mock_val = 'membership_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_membership_flattened_error_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_membership( + membership.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + membership.DeleteMembershipRequest, + dict, +]) +def test_delete_membership(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_membership_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 = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + client.delete_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + +@pytest.mark.asyncio +async def test_delete_membership_async(transport: str = 'grpc_asyncio', request_type=membership.DeleteMembershipRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_membership_async_from_dict(): + await test_delete_membership_async(request_type=dict) + + +def test_delete_membership_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_membership(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_membership_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.DeleteMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_membership(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_membership_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__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_membership( + 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_membership_flattened_error(): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_membership_flattened_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), + '__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_membership( + 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_membership_flattened_error_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + membership.UpdateMembershipRequest, + dict, +]) +def test_update_membership(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.UpdateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_membership_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 = GkeHubMembershipServiceClient( + 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_membership), + '__call__') as call: + client.update_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.UpdateMembershipRequest() + +@pytest.mark.asyncio +async def test_update_membership_async(transport: str = 'grpc_asyncio', request_type=membership.UpdateMembershipRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_membership), + '__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_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.UpdateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_membership_async_from_dict(): + await test_update_membership_async(request_type=dict) + + +def test_update_membership_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.UpdateMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_membership(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_update_membership_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.UpdateMembershipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_membership(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_update_membership_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__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_membership( + name='name_value', + resource=membership.Membership(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].resource + mock_val = membership.Membership(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_membership_flattened_error(): + client = GkeHubMembershipServiceClient( + 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_membership( + membership.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_membership_flattened_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), + '__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_membership( + name='name_value', + resource=membership.Membership(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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].resource + mock_val = membership.Membership(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_membership_flattened_error_async(): + client = GkeHubMembershipServiceAsyncClient( + 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_membership( + membership.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + membership.GenerateConnectManifestRequest, + dict, +]) +def test_generate_connect_manifest(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_connect_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.GenerateConnectManifestResponse( + ) + response = client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateConnectManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_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 = GkeHubMembershipServiceClient( + 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_connect_manifest), + '__call__') as call: + client.generate_connect_manifest() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateConnectManifestRequest() + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async(transport: str = 'grpc_asyncio', request_type=membership.GenerateConnectManifestRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_connect_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.GenerateConnectManifestResponse( + )) + response = await client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateConnectManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateConnectManifestResponse) + + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async_from_dict(): + await test_generate_connect_manifest_async(request_type=dict) + + +def test_generate_connect_manifest_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.GenerateConnectManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), + '__call__') as call: + call.return_value = membership.GenerateConnectManifestResponse() + client.generate_connect_manifest(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_connect_manifest_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.GenerateConnectManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.GenerateConnectManifestResponse()) + await client.generate_connect_manifest(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", [ + membership.ValidateExclusivityRequest, + dict, +]) +def test_validate_exclusivity(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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.validate_exclusivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ValidateExclusivityResponse( + ) + response = client.validate_exclusivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ValidateExclusivityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.ValidateExclusivityResponse) + + +def test_validate_exclusivity_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 = GkeHubMembershipServiceClient( + 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.validate_exclusivity), + '__call__') as call: + client.validate_exclusivity() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ValidateExclusivityRequest() + +@pytest.mark.asyncio +async def test_validate_exclusivity_async(transport: str = 'grpc_asyncio', request_type=membership.ValidateExclusivityRequest): + client = GkeHubMembershipServiceAsyncClient( + 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.validate_exclusivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.ValidateExclusivityResponse( + )) + response = await client.validate_exclusivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ValidateExclusivityRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.ValidateExclusivityResponse) + + +@pytest.mark.asyncio +async def test_validate_exclusivity_async_from_dict(): + await test_validate_exclusivity_async(request_type=dict) + + +def test_validate_exclusivity_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.ValidateExclusivityRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_exclusivity), + '__call__') as call: + call.return_value = membership.ValidateExclusivityResponse() + client.validate_exclusivity(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_validate_exclusivity_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.ValidateExclusivityRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_exclusivity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.ValidateExclusivityResponse()) + await client.validate_exclusivity(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", [ + membership.GenerateExclusivityManifestRequest, + dict, +]) +def test_generate_exclusivity_manifest(request_type, transport: str = 'grpc'): + client = GkeHubMembershipServiceClient( + 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_exclusivity_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = membership.GenerateExclusivityManifestResponse( + crd_manifest='crd_manifest_value', + cr_manifest='cr_manifest_value', + ) + response = client.generate_exclusivity_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateExclusivityManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateExclusivityManifestResponse) + assert response.crd_manifest == 'crd_manifest_value' + assert response.cr_manifest == 'cr_manifest_value' + + +def test_generate_exclusivity_manifest_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 = GkeHubMembershipServiceClient( + 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_exclusivity_manifest), + '__call__') as call: + client.generate_exclusivity_manifest() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateExclusivityManifestRequest() + +@pytest.mark.asyncio +async def test_generate_exclusivity_manifest_async(transport: str = 'grpc_asyncio', request_type=membership.GenerateExclusivityManifestRequest): + client = GkeHubMembershipServiceAsyncClient( + 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_exclusivity_manifest), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(membership.GenerateExclusivityManifestResponse( + crd_manifest='crd_manifest_value', + cr_manifest='cr_manifest_value', + )) + response = await client.generate_exclusivity_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GenerateExclusivityManifestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateExclusivityManifestResponse) + assert response.crd_manifest == 'crd_manifest_value' + assert response.cr_manifest == 'cr_manifest_value' + + +@pytest.mark.asyncio +async def test_generate_exclusivity_manifest_async_from_dict(): + await test_generate_exclusivity_manifest_async(request_type=dict) + + +def test_generate_exclusivity_manifest_field_headers(): + client = GkeHubMembershipServiceClient( + 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 = membership.GenerateExclusivityManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_exclusivity_manifest), + '__call__') as call: + call.return_value = membership.GenerateExclusivityManifestResponse() + client.generate_exclusivity_manifest(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_exclusivity_manifest_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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 = membership.GenerateExclusivityManifestRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_exclusivity_manifest), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(membership.GenerateExclusivityManifestResponse()) + await client.generate_exclusivity_manifest(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", [ + membership.ListMembershipsRequest, + dict, +]) +def test_list_memberships_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse( + 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 = membership.ListMembershipsResponse.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_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_memberships_rest_required_fields(request_type=membership.ListMembershipsRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.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_memberships(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_memberships._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_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_list_memberships") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_list_memberships") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ListMembershipsRequest.pb(membership.ListMembershipsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.ListMembershipsResponse.to_json(membership.ListMembershipsResponse()) + + request = membership.ListMembershipsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ListMembershipsResponse() + + client.list_memberships(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request(transport: str = 'rest', request_type=membership.ListMembershipsRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + + # 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 = membership.ListMembershipsResponse.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_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/memberships" % client.transport._host, args[1]) + + +def test_list_memberships_rest_flattened_error(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_memberships( + membership.ListMembershipsRequest(), + parent='parent_value', + ) + + +def test_list_memberships_rest_pager(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token='abc', + ), + membership.ListMembershipsResponse( + resources=[], + next_page_token='def', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token='ghi', + ), + membership.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(membership.ListMembershipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) + for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + membership.GetMembershipRequest, + dict, +]) +def test_get_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership( + name='name_value', + description='description_value', + external_id='external_id_value', + unique_id='unique_id_value', + infrastructure_type=membership.Membership.InfrastructureType.ON_PREM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.external_id == 'external_id_value' + assert response.unique_id == 'unique_id_value' + assert response.infrastructure_type == membership.Membership.InfrastructureType.ON_PREM + + +def test_get_membership_rest_required_fields(request_type=membership.GetMembershipRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_get_membership") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_get_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GetMembershipRequest.pb(membership.GetMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json(membership.Membership()) + + request = membership.GetMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.get_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_membership_rest_bad_request(transport: str = 'rest', request_type=membership.GetMembershipRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_membership(request) + + +def test_get_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.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_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_get_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_membership( + membership.GetMembershipRequest(), + name='name_value', + ) + + +def test_get_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.CreateMembershipRequest, + dict, +]) +def test_create_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["resource"] = {'name': 'name_value', 'labels': {}, 'description': 'description_value', 'endpoint': {'gke_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'on_prem_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True, 'admin_cluster': True, 'cluster_type': 1}, 'multi_cloud_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'edge_cluster': {'resource_link': 'resource_link_value'}, 'appliance_cluster': {'resource_link': 'resource_link_value'}, 'kubernetes_metadata': {'kubernetes_api_server_version': 'kubernetes_api_server_version_value', 'node_provider_id': 'node_provider_id_value', 'node_count': 1070, 'vcpu_count': 1094, 'memory_mb': 967, 'update_time': {'seconds': 751, 'nanos': 543}}, 'kubernetes_resource': {'membership_cr_manifest': 'membership_cr_manifest_value', 'membership_resources': [{'manifest': 'manifest_value', 'cluster_scoped': True}], 'connect_resources': {}, 'resource_options': {'connect_version': 'connect_version_value', 'v1beta1_crd': True, 'k8s_version': 'k8s_version_value'}}}, 'state': {'code': 1, 'description': 'description_value', 'update_time': {}}, 'authority': {'issuer': 'issuer_value', 'workload_identity_pool': 'workload_identity_pool_value', 'identity_provider': 'identity_provider_value', 'oidc_jwks': b'oidc_jwks_blob'}, 'create_time': {}, 'update_time': {}, 'delete_time': {}, 'external_id': 'external_id_value', 'last_connection_time': {}, 'unique_id': 'unique_id_value', 'infrastructure_type': 1, 'monitoring_config': {'project_id': 'project_id_value', 'location': 'location_value', 'cluster': 'cluster_value', 'kubernetes_metrics_prefix': 'kubernetes_metrics_prefix_value', 'cluster_hash': 'cluster_hash_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 = membership.CreateMembershipRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_membership_rest_required_fields(request_type=membership.CreateMembershipRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "membershipId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == request_init["membership_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["membershipId"] = 'membership_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("membership_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == 'membership_id_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_membership(request) + + expected_params = [ + ( + "membershipId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("membershipId", "requestId", )) & set(("parent", "membershipId", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_create_membership") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_create_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.CreateMembershipRequest.pb(membership.CreateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = membership.CreateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request(transport: str = 'rest', request_type=membership.CreateMembershipRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_membership(request) + + +def test_create_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/memberships" % client.transport._host, args[1]) + + +def test_create_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_membership( + membership.CreateMembershipRequest(), + parent='parent_value', + resource=membership.Membership(name='name_value'), + membership_id='membership_id_value', + ) + + +def test_create_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.DeleteMembershipRequest, + dict, +]) +def test_delete_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_membership_rest_required_fields(request_type=membership.DeleteMembershipRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", "requestId", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_delete_membership") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_delete_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.DeleteMembershipRequest.pb(membership.DeleteMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = membership.DeleteMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request(transport: str = 'rest', request_type=membership.DeleteMembershipRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_delete_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + membership.DeleteMembershipRequest(), + name='name_value', + ) + + +def test_delete_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.UpdateMembershipRequest, + dict, +]) +def test_update_membership_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request_init["resource"] = {'name': 'name_value', 'labels': {}, 'description': 'description_value', 'endpoint': {'gke_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'on_prem_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True, 'admin_cluster': True, 'cluster_type': 1}, 'multi_cloud_cluster': {'resource_link': 'resource_link_value', 'cluster_missing': True}, 'edge_cluster': {'resource_link': 'resource_link_value'}, 'appliance_cluster': {'resource_link': 'resource_link_value'}, 'kubernetes_metadata': {'kubernetes_api_server_version': 'kubernetes_api_server_version_value', 'node_provider_id': 'node_provider_id_value', 'node_count': 1070, 'vcpu_count': 1094, 'memory_mb': 967, 'update_time': {'seconds': 751, 'nanos': 543}}, 'kubernetes_resource': {'membership_cr_manifest': 'membership_cr_manifest_value', 'membership_resources': [{'manifest': 'manifest_value', 'cluster_scoped': True}], 'connect_resources': {}, 'resource_options': {'connect_version': 'connect_version_value', 'v1beta1_crd': True, 'k8s_version': 'k8s_version_value'}}}, 'state': {'code': 1, 'description': 'description_value', 'update_time': {}}, 'authority': {'issuer': 'issuer_value', 'workload_identity_pool': 'workload_identity_pool_value', 'identity_provider': 'identity_provider_value', 'oidc_jwks': b'oidc_jwks_blob'}, 'create_time': {}, 'update_time': {}, 'delete_time': {}, 'external_id': 'external_id_value', 'last_connection_time': {}, 'unique_id': 'unique_id_value', 'infrastructure_type': 1, 'monitoring_config': {'project_id': 'project_id_value', 'location': 'location_value', 'cluster': 'cluster_value', 'kubernetes_metrics_prefix': 'kubernetes_metrics_prefix_value', 'cluster_hash': 'cluster_hash_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 = membership.UpdateMembershipRequest.meta.fields["resource"] + + 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["resource"].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["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][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_membership(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_membership_rest_required_fields(request_type=membership.UpdateMembershipRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_membership(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("name", "updateMask", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_update_membership") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_update_membership") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.UpdateMembershipRequest.pb(membership.UpdateMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = membership.UpdateMembershipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_membership(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_membership_rest_bad_request(transport: str = 'rest', request_type=membership.UpdateMembershipRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_membership(request) + + +def test_update_membership_rest_flattened(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + resource=membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/memberships/*}" % client.transport._host, args[1]) + + +def test_update_membership_rest_flattened_error(transport: str = 'rest'): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership( + membership.UpdateMembershipRequest(), + name='name_value', + resource=membership.Membership(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_membership_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.GenerateConnectManifestRequest, + dict, +]) +def test_generate_connect_manifest_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.GenerateConnectManifestResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.GenerateConnectManifestResponse.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_connect_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateConnectManifestResponse) + + +def test_generate_connect_manifest_rest_required_fields(request_type=membership.GenerateConnectManifestRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_connect_manifest._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_connect_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("connect_agent", "image_pull_secret_content", "is_upgrade", "registry", "version", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.GenerateConnectManifestResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.GenerateConnectManifestResponse.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_connect_manifest(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_connect_manifest_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) + assert set(unset_fields) == (set(("connectAgent", "imagePullSecretContent", "isUpgrade", "registry", "version", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_connect_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_generate_connect_manifest") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_generate_connect_manifest") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GenerateConnectManifestRequest.pb(membership.GenerateConnectManifestRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.GenerateConnectManifestResponse.to_json(membership.GenerateConnectManifestResponse()) + + request = membership.GenerateConnectManifestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.GenerateConnectManifestResponse() + + client.generate_connect_manifest(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_connect_manifest_rest_bad_request(transport: str = 'rest', request_type=membership.GenerateConnectManifestRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_connect_manifest(request) + + +def test_generate_connect_manifest_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.ValidateExclusivityRequest, + dict, +]) +def test_validate_exclusivity_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.ValidateExclusivityResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.ValidateExclusivityResponse.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.validate_exclusivity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.ValidateExclusivityResponse) + + +def test_validate_exclusivity_rest_required_fields(request_type=membership.ValidateExclusivityRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["intended_membership"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "intendedMembership" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_exclusivity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "intendedMembership" in jsonified_request + assert jsonified_request["intendedMembership"] == request_init["intended_membership"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["intendedMembership"] = 'intended_membership_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_exclusivity._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cr_manifest", "intended_membership", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "intendedMembership" in jsonified_request + assert jsonified_request["intendedMembership"] == 'intended_membership_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ValidateExclusivityResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.ValidateExclusivityResponse.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.validate_exclusivity(request) + + expected_params = [ + ( + "intendedMembership", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_validate_exclusivity_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.validate_exclusivity._get_unset_required_fields({}) + assert set(unset_fields) == (set(("crManifest", "intendedMembership", )) & set(("parent", "intendedMembership", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_exclusivity_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_validate_exclusivity") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_validate_exclusivity") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ValidateExclusivityRequest.pb(membership.ValidateExclusivityRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.ValidateExclusivityResponse.to_json(membership.ValidateExclusivityResponse()) + + request = membership.ValidateExclusivityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ValidateExclusivityResponse() + + client.validate_exclusivity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_validate_exclusivity_rest_bad_request(transport: str = 'rest', request_type=membership.ValidateExclusivityRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.validate_exclusivity(request) + + +def test_validate_exclusivity_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + membership.GenerateExclusivityManifestRequest, + dict, +]) +def test_generate_exclusivity_manifest_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = membership.GenerateExclusivityManifestResponse( + crd_manifest='crd_manifest_value', + cr_manifest='cr_manifest_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.GenerateExclusivityManifestResponse.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_exclusivity_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.GenerateExclusivityManifestResponse) + assert response.crd_manifest == 'crd_manifest_value' + assert response.cr_manifest == 'cr_manifest_value' + + +def test_generate_exclusivity_manifest_rest_required_fields(request_type=membership.GenerateExclusivityManifestRequest): + transport_class = transports.GkeHubMembershipServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_exclusivity_manifest._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_exclusivity_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("cr_manifest", "crd_manifest", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.GenerateExclusivityManifestResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.GenerateExclusivityManifestResponse.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_exclusivity_manifest(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_exclusivity_manifest_rest_unset_required_fields(): + transport = transports.GkeHubMembershipServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_exclusivity_manifest._get_unset_required_fields({}) + assert set(unset_fields) == (set(("crManifest", "crdManifest", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_exclusivity_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubMembershipServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubMembershipServiceRestInterceptor(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "post_generate_exclusivity_manifest") as post, \ + mock.patch.object(transports.GkeHubMembershipServiceRestInterceptor, "pre_generate_exclusivity_manifest") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GenerateExclusivityManifestRequest.pb(membership.GenerateExclusivityManifestRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.GenerateExclusivityManifestResponse.to_json(membership.GenerateExclusivityManifestResponse()) + + request = membership.GenerateExclusivityManifestRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.GenerateExclusivityManifestResponse() + + client.generate_exclusivity_manifest(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_exclusivity_manifest_rest_bad_request(transport: str = 'rest', request_type=membership.GenerateExclusivityManifestRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_exclusivity_manifest(request) + + +def test_generate_exclusivity_manifest_rest_error(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubMembershipServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GkeHubMembershipServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubMembershipServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + transports.GkeHubMembershipServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = GkeHubMembershipServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GkeHubMembershipServiceGrpcTransport, + ) + +def test_gke_hub_membership_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GkeHubMembershipServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_gke_hub_membership_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GkeHubMembershipServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_memberships', + 'get_membership', + 'create_membership', + 'delete_membership', + 'update_membership', + 'generate_connect_manifest', + 'validate_exclusivity', + 'generate_exclusivity_manifest', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_gke_hub_membership_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubMembershipServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_gke_hub_membership_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.gkehub_v1beta1.services.gke_hub_membership_service.transports.GkeHubMembershipServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GkeHubMembershipServiceTransport() + adc.assert_called_once() + + +def test_gke_hub_membership_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GkeHubMembershipServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + ], +) +def test_gke_hub_membership_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubMembershipServiceGrpcTransport, + transports.GkeHubMembershipServiceGrpcAsyncIOTransport, + transports.GkeHubMembershipServiceRestTransport, + ], +) +def test_gke_hub_membership_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.GkeHubMembershipServiceGrpcTransport, grpc_helpers), + (transports.GkeHubMembershipServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_gke_hub_membership_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "gkehub.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="gkehub.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.GkeHubMembershipServiceGrpcTransport, transports.GkeHubMembershipServiceGrpcAsyncIOTransport]) +def test_gke_hub_membership_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_gke_hub_membership_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.GkeHubMembershipServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_gke_hub_membership_service_rest_lro_client(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_gke_hub_membership_service_host_no_port(transport_name): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkehub.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkehub.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkehub.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_gke_hub_membership_service_host_with_port(transport_name): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='gkehub.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'gkehub.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://gkehub.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_gke_hub_membership_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GkeHubMembershipServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GkeHubMembershipServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.update_membership._session + session2 = client2.transport.update_membership._session + assert session1 != session2 + session1 = client1.transport.generate_connect_manifest._session + session2 = client2.transport.generate_connect_manifest._session + assert session1 != session2 + session1 = client1.transport.validate_exclusivity._session + session2 = client2.transport.validate_exclusivity._session + assert session1 != session2 + session1 = client1.transport.generate_exclusivity_manifest._session + session2 = client2.transport.generate_exclusivity_manifest._session + assert session1 != session2 +def test_gke_hub_membership_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubMembershipServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_gke_hub_membership_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GkeHubMembershipServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.GkeHubMembershipServiceGrpcTransport, transports.GkeHubMembershipServiceGrpcAsyncIOTransport]) +def test_gke_hub_membership_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.GkeHubMembershipServiceGrpcTransport, transports.GkeHubMembershipServiceGrpcAsyncIOTransport]) +def test_gke_hub_membership_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_gke_hub_membership_service_grpc_lro_client(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_gke_hub_membership_service_grpc_lro_async_client(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_membership_path(): + project = "squid" + location = "clam" + membership = "whelk" + expected = "projects/{project}/locations/{location}/memberships/{membership}".format(project=project, location=location, membership=membership, ) + actual = GkeHubMembershipServiceClient.membership_path(project, location, membership) + assert expected == actual + + +def test_parse_membership_path(): + expected = { + "project": "octopus", + "location": "oyster", + "membership": "nudibranch", + } + path = GkeHubMembershipServiceClient.membership_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_membership_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GkeHubMembershipServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = GkeHubMembershipServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = GkeHubMembershipServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = GkeHubMembershipServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GkeHubMembershipServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = GkeHubMembershipServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = GkeHubMembershipServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = GkeHubMembershipServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = GkeHubMembershipServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = GkeHubMembershipServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubMembershipServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.GkeHubMembershipServiceTransport, '_prep_wrapped_messages') as prep: + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GkeHubMembershipServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = GkeHubMembershipServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = GkeHubMembershipServiceClient( + 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.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = GkeHubMembershipServiceClient( + 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 = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/memberships/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/memberships/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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 = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/memberships/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/memberships/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = GkeHubMembershipServiceClient( + 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.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = GkeHubMembershipServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = GkeHubMembershipServiceClient( + 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.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = GkeHubMembershipServiceClient( + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + 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_delete_operation(transport: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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 response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = GkeHubMembershipServiceAsyncClient( + 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.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_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 response is None + +def test_delete_operation_field_headers(): + client = GkeHubMembershipServiceClient( + 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_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_delete_operation_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_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_delete_operation_from_dict(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_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 response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = GkeHubMembershipServiceAsyncClient( + 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.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_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 response is None + +def test_cancel_operation_field_headers(): + client = GkeHubMembershipServiceClient( + 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_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_cancel_operation_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_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_cancel_operation_from_dict(): + client = GkeHubMembershipServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = GkeHubMembershipServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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"): + client = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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"): + client = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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"): + client = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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_get_location(transport: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(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.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = GkeHubMembershipServiceAsyncClient( + 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.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(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.Location) + +def test_get_location_field_headers(): + client = GkeHubMembershipServiceClient( + 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.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(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/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = GkeHubMembershipServiceAsyncClient( + 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.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = GkeHubMembershipServiceClient( + 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.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = GkeHubMembershipServiceAsyncClient( + 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.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceAsyncClient( + 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 = GkeHubMembershipServiceClient( + 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 = GkeHubMembershipServiceClient( + 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", [ + (GkeHubMembershipServiceClient, transports.GkeHubMembershipServiceGrpcTransport), + (GkeHubMembershipServiceAsyncClient, transports.GkeHubMembershipServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )